Created
October 21, 2018 18:11
-
-
Save geminorum/98b49f9eb6d58fefa8e522ed25190c85 to your computer and use it in GitHub Desktop.
Week numbers in JavaScript
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
/// How to get the week number from a date | |
// The code below adds two new functions to the Date object. Add this to your source code. | |
// To get the ISO week number (1-53) of a Date object, mydate, use mydate.getWeek(). | |
// To get the corresponding four-digit year, use mydate.getWeekYear(). | |
// This script is released to the public domain and may be used, modified and | |
// distributed without restrictions. Attribution not necessary but appreciated. | |
// @SOURCE: https://weeknumber.net/how-to/javascript | |
// Returns the ISO week of the date. | |
Date.prototype.getWeek = function() { | |
var date = new Date(this.getTime()); | |
date.setHours(0, 0, 0, 0); | |
// Thursday in current week decides the year. | |
date.setDate(date.getDate() + 3 - (date.getDay() + 6) % 7); | |
// January 4 is always in week 1. | |
var week1 = new Date(date.getFullYear(), 0, 4); | |
// Adjust to Thursday in week 1 and count number of weeks from date to week1. | |
return 1 + Math.round(((date.getTime() - week1.getTime()) / 86400000 | |
- 3 + (week1.getDay() + 6) % 7) / 7); | |
} | |
// Returns the four-digit year corresponding to the ISO week of the date. | |
Date.prototype.getWeekYear = function() { | |
var date = new Date(this.getTime()); | |
date.setDate(date.getDate() + 3 - (date.getDay() + 6) % 7); | |
return date.getFullYear(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment