Skip to content

Instantly share code, notes, and snippets.

@jrrio
Last active January 17, 2021 13:38
Show Gist options
  • Save jrrio/6ccb78c9f7bfe2a310c0b68f30779ece to your computer and use it in GitHub Desktop.
Save jrrio/6ccb78c9f7bfe2a310c0b68f30779ece to your computer and use it in GitHub Desktop.
Date Utilities in vanilla JavaScript
/**
*
* @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