Last active
August 6, 2020 04:31
-
-
Save bytrangle/a8394ab72047296f2031b2a023c28324 to your computer and use it in GitHub Desktop.
Create an array of weeks with start and end week date from a given start date to today. No external libraries.
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
// Add 0 to date value smaller than 10. For example, date 8 of July will become 07-08. | |
function padDate(number) { | |
return number < 10 ? '0' + number.toString() : number.toString(); | |
} | |
// format the date object as YYYY-MM-DD | |
function formatDate(date) { | |
const yr = date.getFullYear(); | |
const mo = padDate(date.getMonth() + 1); | |
const da = padDate(date.getDate()); | |
return `${yr}-${mo}-${da}`; | |
} | |
function getWeekArray(givenDate) { | |
// turn the startDate into a Date object | |
const given = new Date(givenDate); | |
const givenCp = new Date(given); | |
// Find the number that we have to subtract from the start date to arrive at the previous Monday | |
const offset = (given.getDay() + 6) % 7; | |
// Get the Monday in the same week as the start date in milliseconds | |
const earliestMonInMillisecs = givenCp.setDate(givenCp.getDate() - offset) | |
const earliestMon = new Date(earliestMonInMillisecs); | |
console.log('earliest mon is ', earliestMon); | |
let weeks = []; | |
// Save the earliest Monday to a new temporary variable | |
let start = new Date(earliestMon); | |
let _start = new Date(start); | |
let sun = new Date(_start.setDate(_start.getDate() + 6)); | |
console.log(sun); | |
const now = new Date(); | |
while (sun < now) { | |
const from = formatDate(start); | |
const to = formatDate(sun); | |
weeks.push({from, to}); | |
start = new Date(start.setDate(start.getDate() + 7)); | |
sun = new Date(sun.setDate(sun.getDate() + 7)); | |
console.log('next sun is ', sun); | |
} | |
console.log('given date is ', given); | |
return weeks; | |
} | |
console.log(getWeekArray('2020-07-06T13:22:09.000Z')); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment