-2

how to get week number of a year where sunday as the first day of a week in javascript, also the fixed year number?

e.g. 2012-12-31 should have the same year number and week number with 2013-01-01.

I found a snippet to do this, but the week is always start from monday not sunday, how to fix it?

exports.getYearAndWeek = function(d) {
    // Copy date so don't modify original
    d = new Date(d);
    d.setHours(0,0,0);
    // Set to nearest Thursday: current date + 4 - current day number
    // Make Sunday's day number 7
    d.setDate(d.getDate() + 4 - (d.getDay()||7));
    // Get first day of year
    var yearStart = new Date(d.getFullYear(),0,1);
    // Calculate full weeks to nearest Thursday
    var weekNo = Math.ceil(( ( (d - yearStart) / 86400000) + 1)/7)
    // Return array of year and week number
    return [d.getFullYear(), weekNo];
}
4

1 回答 1

0

The first week of a year, for weeks starting with Monday, is the first week that has a Thursday in it, as your code suggests.

If your weeks start with Sunday, the first week will be the first week containing a Wednesday.

If the year starts on Thursday to Saturday the days until Sunday will be in the last week of the previous year. If the year starts on Monday, Tuesday or Wednesday, the last Sunday of the previous year is the beginning of the first week of this year.

于 2012-09-11T03:47:41.247 回答