Skip to content

Instantly share code, notes, and snippets.

@glumn
Last active August 29, 2015 14:22
Show Gist options
  • Select an option

  • Save glumn/6c8813ee08dca845d4af to your computer and use it in GitHub Desktop.

Select an option

Save glumn/6c8813ee08dca845d4af to your computer and use it in GitHub Desktop.
Gives back the week start date and end date, provided a week number, year, and starting day (Using moment)
// 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 };
},
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment