I wrote two simple functions to play around with Moment.js.

The first function returns a week as an array of dates, given one arbitrary day in that week.

var getWeek = function (day) {
    var today = day.clone();
    var monday = today.clone().startOf('isoWeek');
    var sunday = today.clone().endOf('isoWeek');
    var days = [];
    for (var current = monday.clone(); current.isBefore(today, 'day'); 
             current.add(1, 'days')) {
         days.push(current.format());
    }

    days.push(today.format());

    for (var current = today.clone().add(1, 'days');
         current.isBefore(sunday, 'day') || 
         (current.isSame(sunday, 'day') &&!today.isSame(sunday, 'day'));
       current.add(1, 'days')) {
       days.push(current.format());
    }

    return days;
};

The second function returns the number of week of the year given an arbitrary day.

var dayofweek = function (day) {
    return Math.ceil(moment(day).dayOfYear() / 7);
};

However, when I test it by passing today as moment() I get the correct result, 15. When I test it by passing getWeek(moment())[0] (which is Monday), I get 14.

JSFiddle

I suspect this has to do with timezones, or something like that, but I know pretty much nothing about how these things work. Can someone figure it out?

有帮助吗?

解决方案

Your algorithm for calculating the week number is incorrect. (Also the name dayofweek is a little confusing).

You need to use

floor((dayOfYear(date) - dayOfWeek(date) + 10) / 7);

Where dayOfYear returns 1-366 and dayOfWeek returns 1-7 (Mon-Sun).

However, since you're already using moment.js, why not just use .isoWeek()?

Updated JSFiddle.

Source: ISO Week Date (Wikipedia)

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top