• 2024-11-22
宇哥博客 前端开发 JS获取本周第一天和最后一天日期

JS获取本周第一天和最后一天日期

获取本周第一天和最后一天,中国地区一般以周一为一周的第一天,周日为最后一天,也就是本周的周一和周日。

/**
       * 获取本周的第一天
       * 返回格式: YYYY-mm-dd
       * 
       */
      function getCurrentWeekFirstDay(date) {
    	  var days=date.getDay();
    	  days=days==0?7:days;
    	  
          let weekFirstDay = new Date(date - (days - 1) * 86400000 );
          //console.log('===', weekFirstDay);
          let firstMonth = Number(weekFirstDay.getMonth()) + 1;
          if (firstMonth < 10) {
              firstMonth = '0' + firstMonth;
          }
          let weekFirstDays = weekFirstDay.getDate();
          if (weekFirstDays < 10) {
              weekFirstDays = '0' + weekFirstDays;
          }
          return weekFirstDay.getFullYear() + '-' + firstMonth + '-' + weekFirstDays;
      }
  
      /**
       * 获取本周的最后一天
       * 返回格式: YYYY-mm-dd
       * 
       */
      function getCurrentWeekLastDay(date) {
    	  var days=date.getDay();
    	  days=days==0?7:days;
    	  
          let weekFirstDay = new Date(date - (days - 1) * 86400000);
          let weekLastDay = new Date((weekFirstDay / 1000 + 6 * 86400) * 1000);
          let lastMonth = Number(weekLastDay.getMonth()) + 1;
          if (lastMonth < 10) {
              lastMonth = '0' + lastMonth;
          }
          let weekLastDays = weekLastDay.getDate();
          if (weekLastDays < 10) {
              weekLastDays = '0' + weekLastDays;
          }
          return weekLastDay.getFullYear() + '-' + lastMonth + '-' + weekLastDays;
      }

测试效果:

getCurrentWeekFirstDay(new Date('2022-03-02'))
'2022-02-28'
getCurrentWeekFirstDay(new Date('2022-01-02'))
'2021-12-27'
getCurrentWeekLastDay(new Date('2022-01-02'))
'2022-01-02'
getCurrentWeekLastDay(new Date('2022-01-11'))
'2022-01-16'

本文来自网络,不代表本站立场,转载请注明出处。https://www.ygbks.com/1369.html

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注

返回顶部