how to get the ISO week of year using javascript

If January 1st is Monday, Tuesday, Wednesday, Thursday, It's belong to first ISO week

Else if it's Friday, Saturday, Sunday ,then it belong to the week of last year.


if (!Array.prototype.forEach) {
    Array.prototype.forEach = function (df) {
        var i = 0,
        s = this.length;
        for (; i < s; i++) {
            cf && cf(this[i], i, this);
        }
    }
}

// ISO week algorithm is mainly used in government, business and enterprise production
// It's written like 2009-W53-5 2010-01-01. 
// If January 1st is under Thursday (inclusive), then it belongs to the first week.
// for example:  2009-01-01. is Thursday, Corresponds to the 4th day of the 1th week of 2009, 
// So 2008-12-31 is the 3rd day of the 1th week of 2009.

Date.prototype.getISOWeek = function () {
var newDate = new Date(Date.UTC(this.getFullYear(), this.getMonth(), this.getDate()));
var Day = newDate.getUTCDay()||7;
newDate.setUTCDate(newDate.getUTCDate() + 4 - (newDate.getUTCDay() || 7));
var Year = newDate.getFullYear();
var yearFirstDate = new Date(Date.UTC(Year, 0, 1));
var WeekNum = Math.ceil((((newDate - yearFirstDate) / 86400000) + 1) / 7);
// you can format it like this  2009-W53-5 
console.log(Year+"-W"+WeekNum+"-"+Day);
// return the week number
return WeekNum;
}

// ====== how to use ========
// var today = new Date();
// var weekNumber = today.getISOWeek(); // get the iso week that today belong to
// console.log(weekNumber); 
// ==============

// ====== test code ========

var testDates = ['2005-1-1', '2005-1-2', '2005-12-31', '2006-1-1', '2006-1-2', '2006-12-31', '2007-1-1', '2007-12-30',
'2007-12-31', '2008-1-1', '2008-12-28', '2008-12-29', '2008-12-30', '2008-12-31', '2009-1-1', '2009-12-31', '2010-1-1',
'2010-1-2', '2010-1-3'
];
// expectations  '2004-W53-6','2004-W53-7','2005-W52-6','2005-W52-7','2006-W01-1','2006-W52-7','2007-W01-1','2007-W52-7',
// '2008-W01-1','2008-W01-2','2008-W52-7','2009-W01-1','2009-W01-2','2009-W01-3','2009-W01-4','2009-W53-4','2009-W53-5',
// '2009-W53-6','2009-W53-7'

testDates.forEach(function (testdate) {
    var d = new Date(testdate);
    console.log(d.getISOWeek());
});

// ======test code end ========


date2018-12-23 20:31:25 From:www.jquerypluginhub.com Author:JPH
Related Tags:
Comments

Leave a Reply

Your email address will not be published. Required fields are marked *