Get week of year in JavaScript like in PHP

后端 未结 19 1361
南方客
南方客 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 02:50

    Get the weeknumber of any given Date

    function week(year,month,day) {
        function serial(days) { return 86400000*days; }
        function dateserial(year,month,day) { return (new Date(year,month-1,day).valueOf()); }
        function weekday(date) { return (new Date(date)).getDay()+1; }
        function yearserial(date) { return (new Date(date)).getFullYear(); }
        var date = year instanceof Date ? year.valueOf() : typeof year === "string" ? new Date(year).valueOf() : dateserial(year,month,day), 
            date2 = dateserial(yearserial(date - serial(weekday(date-serial(1))) + serial(4)),1,3);
        return ~~((date - date2 + serial(weekday(date2) + 5))/ serial(7));
    }
    

    Example

    console.log(
        week(2016, 06, 11),//23
        week(2015, 9, 26),//39
        week(2016, 1, 1),//53
        week(2016, 1, 4),//1
        week(new Date(2016, 0, 4)),//1
        week("11 january 2016")//2
    );
    

提交回复
热议问题