Get week of year in JavaScript like in PHP

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

    Not ISO-8601 week number but if the search engine pointed you here anyways.

    As said above but without a class:

    let now = new Date();
    let onejan = new Date(now.getFullYear(), 0, 1);
    let week = Math.ceil( (((now.getTime() - onejan.getTime()) / 86400000) + onejan.getDay() + 1) / 7 );
    
    0 讨论(0)
  • 2020-11-22 03:06

    This adds "getWeek" method to Date.prototype which returns number of week from the beginning of the year. The argument defines which day of the week to consider the first. If no argument passed, first day is assumed Sunday.

    /**
     * Get week number in the year.
     * @param  {Integer} [weekStart=0]  First day of the week. 0-based. 0 for Sunday, 6 for Saturday.
     * @return {Integer}                0-based number of week.
     */
    Date.prototype.getWeek = function(weekStart) {
        var januaryFirst = new Date(this.getFullYear(), 0, 1);
        if(weekStart !== undefined && (typeof weekStart !== 'number' || weekStart % 1 !== 0 || weekStart < 0 || weekStart > 6)) {
          throw new Error('Wrong argument. Must be an integer between 0 and 6.');
        }
        weekStart = weekStart || 0;
        return Math.floor((((this - januaryFirst) / 86400000) + januaryFirst.getDay() - weekStart) / 7);
    };
    
    0 讨论(0)
  • 2020-11-22 03:09

    You can use momentjs library also:

    moment().format('W')

    0 讨论(0)
  • 2020-11-22 03:10

    Another library-based option: use d3-time-format:

    const formatter = d3.timeFormat('%U');
    const weekNum = formatter(new Date());
    
    0 讨论(0)
  • 2020-11-22 03:11

    If you are already in an Angular project you could use $filter('date').

    For example:

    var myDate = new Date();
    var myWeek = $filter('date')(myDate, 'ww');
    
    0 讨论(0)
  • 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

    0 讨论(0)
提交回复
热议问题