Last active
January 14, 2018 11:34
-
-
Save vincevargadev/a8ceb710688c22ca575a7f185c875d31 to your computer and use it in GitHub Desktop.
Print next "n" week after a given date in JavaScript
This file contains 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
// Three-letter abbreviations of months | |
const monthAbbrev = 'Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec'.split(' '); | |
// One day in milliseconds. Used for creating new dates "x" days after a given date | |
const dayMs = 24 * 60 * 60 * 1000; | |
// I could have just used toLocaleDateString, but this is more flexible and easier to adjust to your needs | |
const formatDateSimple = d => `${d.getFullYear()} ${monthAbbrev[d.getMonth()]} ${d.getDate()}`; | |
function getWeekStr(startDate, weekCount, formatDate) { | |
const weekRange = new Array(weekCount); | |
for (let i = 0; i < weekCount; i += 1) { | |
const starts = new Date(startDate.getTime() + i * 7 * dayMs); | |
const ends = new Date(startDate.getTime() + 6 * dayMs + i * 7 * dayMs); | |
weekRange[i] = `${formatDate(starts, i)} - ${formatDate(ends, i)}`; | |
} | |
return weekRange.join('\n'); | |
} | |
getWeekStr(new Date(2018, 0, 15), 12, formatDateSimple); | |
/* // Example string return value: | |
2018 Jan 15 - 2018 Jan 21 | |
2018 Jan 22 - 2018 Jan 28 | |
2018 Jan 29 - 2018 Feb 4 | |
2018 Feb 5 - 2018 Feb 11 | |
2018 Feb 12 - 2018 Feb 18 | |
2018 Feb 19 - 2018 Feb 25 | |
2018 Feb 26 - 2018 Mar 4 | |
2018 Mar 5 - 2018 Mar 11 | |
2018 Mar 12 - 2018 Mar 18 | |
2018 Mar 19 - 2018 Mar 25 | |
2018 Mar 26 - 2018 Apr 1 | |
2018 Apr 2 - 2018 Apr 8 | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment