Last active
August 29, 2015 14:22
-
-
Save glumn/6c8813ee08dca845d4af to your computer and use it in GitHub Desktop.
Revisions
-
Guillaume Mantopoulos renamed this gist
Aug 6, 2015 . 1 changed file with 0 additions and 0 deletions.There are no files selected for viewing
File renamed without changes. -
Guillaume Mantopoulos revised this gist
Aug 6, 2015 . No changes.There are no files selected for viewing
-
Guillaume Mantopoulos created this gist
Jun 2, 2015 .There are no files selected for viewing
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 charactersOriginal file line number Diff line number Diff line change @@ -0,0 +1,53 @@ // http://en.wikipedia.org/wiki/ISO_8601#Week_dates // http://stackoverflow.com/questions/662379/calculate-date-from-week-number getDatesFromWeek: function (week, year, startOfWeekDay) { if (startOfWeekDay == undefined || startOfWeekDay == null) startOfWeekDay = 0; // Default StartOfWeek to Sunday if not provided // ISO 8601 defines the week where first Thursday of the year is has Week 1 // create a variable holding the position of thursday in the week var thursday = 4; // First set a basis of january one for the current year var januaryOne = new Date(Date.UTC(year, 0, 1)); // ISO 8601 defines the week where first Thursday of the year is has Week 1 // Calculate the offset of days between the first thursday and January 1 var daysOffset = thursday - januaryOne.getDay(); // Then get the first thursday date var firstThursday = januaryOne; firstThursday.setDate(firstThursday.getDate() + daysOffset); // Later on we will multiply the week we ask for // by 7 days to add to the date, so lower week to 0 if we're asking for first week var firstWeek = moment(firstThursday).isoWeek(); var weekNumber = week; if (firstWeek <= 1) { weekNumber -= 1; } // Match week that was asked for // Add as much days as needed depending on the week we're asking for var startDate = firstThursday; startDate.setDate(startDate.getDate() + (weekNumber * 7)); // Start Date right now is set to thursday, match the start of week day that was asked for by adding / removing days var startDateDayOffset; if (startOfWeekDay == 0) { // If specific start of day is Sunday, add 3 days startDateDayOffset = 3; } else { // Otherwise the offset calculation is simple startDateDayOffset = startOfWeekDay - thursday; } // Apply the calculated offset to get the start date for the provided week given a specific starting day startDate.setDate(startDate.getDate() + startDateDayOffset); // End Date is startDate + 6 var endDate = new Date(Date.UTC(startDate.getFullYear(), startDate.getMonth(), startDate.getDate() + 6)); return { startDate: startDate, endDate: endDate, week: week, year: year }; },