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?