Last active
January 17, 2021 13:38
-
-
Save jrrio/6ccb78c9f7bfe2a310c0b68f30779ece to your computer and use it in GitHub Desktop.
Date Utilities in vanilla 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
/** | |
* | |
* @param date - may be either a Date object or a String representing a Date | |
*/ | |
function lastDayOfMonth(date) { | |
var d = new Date(date); | |
d.setFullYear(d.getFullYear(), d.getMonth() + 1, 0); | |
return d.getDate(); | |
} | |
// Example | |
console.log(lastDayOfMonth('2020-02-14')); // returns 29 | |
function addDays(date, days) { | |
var result = new Date(date); | |
result.setDate(result.getDate() + days); | |
return result; | |
} | |
function addMonths(date, months) { | |
var result = new Date(date); | |
var d = date.getDate(); | |
result.setMonth(result.getMonth() + months); | |
if (result.getDate() != d) { | |
result.setDate(0); // the date will be set to the last day of the previous month | |
} | |
return result; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment