根据具体日期计算是一年的第几周和当月的第几周

版权声明:本文为博主原创文章,未经博主允许不得转载。vasttian https://blog.csdn.net/u012860063/article/details/70337582


根据具体日期计算是一年的第几周:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Document</title>
</head>
<body>
  <script>
    // 计算具体日期为当月的第几周
    function getWeek(str) {
      // 将字符串转为标准时间格式
      str = Date.parse(str);
      str = new Date(str);
      // 先计算出该日期为第几周
      let week = Math.ceil(str.getDate()/7);
      let month = str.getMonth() + 1;
      // 判断这个月前7天是周几,如果不是周一,则计入上个月
      if  (str.getDate() < 7) {
        if (str.getDay() !== 1) {
          week = 5;
          month = str.getMonth();
        }
      }
      console.log(`${month}-${week}`);
    }
    console.log(getWeek('2017-01-01'));
  </script>
</body>
</html>

根据具体日期计算是当月的第几周:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Document</title>
</head>
<body>
  <script>
    const year = String(new Date(Date.parse(date)).getFullYear());
    console.log('year:', year);
    console.log('date:', new Date(year));
    const week =  (((new Date(date)) - (new Date(year))) / (24 * 60 * 60 * 7 * 1000) | 0) + 1;
    console.log('week', week);
  </script>
</body>
</html>


猜你喜欢

转载自blog.csdn.net/u012860063/article/details/70337582