js获取本周时间,当月的日期,计算两个时间差,距离当前日期后几天的日期


前言

本片文章主要记录一下遇到的问题,js计算当前一周的日期。感兴趣的小伙伴可以学习一下。

提示:以下是本篇文章正文内容,下面案例可供参考

一、Date日期对象

Date()日期对象 是一个构造函数,必须使用new 来调用创建我们的日期对象使用Date日期对象的时候,如果里面没有放置参数,那么返回的就是系统的当前时间

常用方法 说明
getFullYear() 返回当前日期的年份
getMonth() 返回当前日期的月份 但是返回值是在0-11,我们需要在获取到的月份上 进行+1的操作
getDate() 返回的是当前日期的天数,也就是今天是几号
getDay() 返回的是今天是星期几 周一返回的是1,周六返回的是6 但是周日返回的是0
getHours() 返回的是当前的小时
getMinutes() 返回的是当前的分钟数
getSeconds() 返回的是当前的秒数
getTime() 获取毫秒数
setFullYear() 为指定日期设置年
setDate() 设置指定的日期
setHours() 设置指定日期设置小时
setMinutes() 设置指定日期的分钟数
setSeconds() 设置指定日期的秒数

二 获取当前一周的日期

要获取当前一周的日期,我们可以先计算周一的日期,然后通过for循环循环6次,就可以得到一周的时间。

  getWeeks() {
   
   
       let weeks = [];
       let currentDate = new Date();
       let day = currentDate.getDay();
       if (day === '0') {
   
   
             currentDate.setDate(currentDate.getDate() - 6);
          } else {
   
   
             currentDate.setDate(currentDate.getDate() - day + 1);
       }
         // 得到周一的日期
       let year = currentDate.getFullYear();
       let month = currentDate.getMonth() + 1 < 10 ? '0' + (currentDate.getMonth() + 1) : currentDate.getMonth() + 1;
       let date = currentDate.getDate() < 10 ? '0' + currentDate.getDate() : currentDate.getDate();
       weeks.push(year + '-' + month + '-' + date);
            
      for (var i = 0; i < 6; i++) {
   
   
          currentDate.setDate(currentDate.getDate() + 1);
          year = currentDate.getFullYear();
          month = currentDate.getMonth() + 1 < 10 ? '0' + (currentDate.getMonth() + 1) : currentDate.getMonth() + 1;
          date = currentDate.getDate() < 10 ? '0' + currentDate.getDate() : currentDate.getDate();
          weeks.push(year + '-' + month + '-' + date);
      }
          console.log(weeks)
评论 32
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

x-z-y

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值