Get week of year in JavaScript like in PHP

后端 未结 19 1305
南方客
南方客 2020-11-22 02:38

How do I get the current weeknumber of the year, like PHP\'s date(\'W\')?

It should be the ISO-8601 week number of year, weeks starting

19条回答
  •  北海茫月
    2020-11-22 03:04

    The code below calculates the correct ISO 8601 week number. It matches PHP's date("W") for every week between 1/1/1970 and 1/1/2100.

    /**
     * Get the ISO week date week number
     */
    Date.prototype.getWeek = function () {
      // Create a copy of this date object
      var target = new Date(this.valueOf());
    
      // ISO week date weeks start on Monday, so correct the day number
      var dayNr = (this.getDay() + 6) % 7;
    
      // ISO 8601 states that week 1 is the week with the first Thursday of that year
      // Set the target date to the Thursday in the target week
      target.setDate(target.getDate() - dayNr + 3);
    
      // Store the millisecond value of the target date
      var firstThursday = target.valueOf();
    
      // Set the target to the first Thursday of the year
      // First, set the target to January 1st
      target.setMonth(0, 1);
    
      // Not a Thursday? Correct the date to the next Thursday
      if (target.getDay() !== 4) {
        target.setMonth(0, 1 + ((4 - target.getDay()) + 7) % 7);
      }
    
      // The week number is the number of weeks between the first Thursday of the year
      // and the Thursday in the target week (604800000 = 7 * 24 * 3600 * 1000)
      return 1 + Math.ceil((firstThursday - target) / 604800000);
    }
    

    Source: Taco van den Broek


    If you're not into extending prototypes, then here's a function:

    function getWeek(date) {
      if (!(date instanceof Date)) date = new Date();
    
      // ISO week date weeks start on Monday, so correct the day number
      var nDay = (date.getDay() + 6) % 7;
    
      // ISO 8601 states that week 1 is the week with the first Thursday of that year
      // Set the target date to the Thursday in the target week
      date.setDate(date.getDate() - nDay + 3);
    
      // Store the millisecond value of the target date
      var n1stThursday = date.valueOf();
    
      // Set the target to the first Thursday of the year
      // First, set the target to January 1st
      date.setMonth(0, 1);
    
      // Not a Thursday? Correct the date to the next Thursday
      if (date.getDay() !== 4) {
        date.setMonth(0, 1 + ((4 - date.getDay()) + 7) % 7);
      }
    
      // The week number is the number of weeks between the first Thursday of the year
      // and the Thursday in the target week (604800000 = 7 * 24 * 3600 * 1000)
      return 1 + Math.ceil((n1stThursday - date) / 604800000);
    }
    

    Sample usage:

    getWeek(); // Returns 37 (or whatever the current week is)
    getWeek(new Date('Jan 2, 2011')); // Returns 52
    getWeek(new Date('Jan 1, 2016')); // Returns 53
    getWeek(new Date('Jan 4, 2016')); // Returns 1
    

提交回复
热议问题