Last active
January 24, 2022 08:40
-
-
Save IamSilviu/5899269 to your computer and use it in GitHub Desktop.
JavaScript Get week number.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Date.prototype.getWeek = function () { | |
var onejan = new Date(this.getFullYear(), 0, 1); | |
return Math.ceil((((this - onejan) / 86400000) + onejan.getDay() + 1) / 7); | |
}; | |
var myDate = new Date("2001-02-02"); | |
myDate.getWeek(); //=> 5 |
Thanks for the function.
There is just small issue that typescript don't validate arithmetic operations on Date
type so shows below error.
The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type
So I've called .valueOf()
on Dates in that arithmetic operation.
getNumberOfWeek(): number {
const today = new Date();
const firstDayOfYear = new Date(today.getFullYear(), 0, 1);
const pastDaysOfYear = (today.valueOf() - firstDayOfYear.valueOf()) / 86400000;
return Math.ceil((pastDaysOfYear + firstDayOfYear.getDay() + 1) / 7);
}
If you want the ISO solution there is a formula here that gives you the # of weeks of a given year:
What will be week for Date ...
2022-01-01, //getDay() returning 6
2022-01-02, //getDay() returning 0
2022-01-03 //getDay() returning 1
As per above method
2022-01-01 is returning week 2 and next 6 dates is part of same week.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks for this 👍