Get week of year in JavaScript like in PHP

后端 未结 19 1809
南方客
南方客 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:12

    getWeekOfYear: function(date) {
            var target = new Date(date.valueOf()),
                dayNumber = (date.getUTCDay() + 6) % 7,
                firstThursday;
    
            target.setUTCDate(target.getUTCDate() - dayNumber + 3);
            firstThursday = target.valueOf();
            target.setUTCMonth(0, 1);
    
            if (target.getUTCDay() !== 4) {
                target.setUTCMonth(0, 1 + ((4 - target.getUTCDay()) + 7) % 7);
            }
    
            return Math.ceil((firstThursday - target) /  (7 * 24 * 3600 * 1000)) + 1;
        }
    

    Following code is timezone-independent (UTC dates used) and works according to the https://en.wikipedia.org/wiki/ISO_8601

提交回复
热议问题