Get week of year in JavaScript like in PHP

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

    I tried a lot to get the shortest code to get the weeknumber ISO-conform.

    Date.prototype.getWeek=function(){
        var date=new Date(this);
        date.setHours(0,0,0,0);
        return Math.round(((date.setDate(this.getDate()+2-(this.getDay()||7))-date.setMonth(0,4))/8.64e7+3+(date.getDay()||7))/7)+"/"+date.getFullYear();}
    

    The variable date is necessary to avoid to alter the original this. I used the return values of setDate() and setMonth() to dispense with getTime() to save code length and I used an expontial number for milliseconds of a day instead of a multiplication of single elements or a number with five zeros. this is Date or Number of milliseconds, return value is String e.g. "49/2017".

提交回复
热议问题