Last active
May 30, 2020 15:37
-
-
Save jherax/bbc43e479a492cc9cbfc7ccc20c53cd2 to your computer and use it in GitHub Desktop.
Adds or subtracts date portions to the given date.
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
/** | |
* Adds or subtracts date portions to the given date and returns the new date. | |
* | |
* @param {Object} options: It contains the date parts to add or remove, and can have the following properties: | |
* - {Date} date: if provided, this date will be affected, otherwise the current date will be used. | |
* - {number} minutes: minutes to add/subtract | |
* - {Number} hours: hours to add/subtract | |
* - {Number} days: days to add/subtract | |
* - {Number} months: months to add/subtract | |
* - {Number} years: years to add/subtract | |
* @return {Date} | |
*/ | |
function alterDate(options = {}) { | |
const opt = Object.assign({}, options); | |
const d = opt.date instanceof Date ? opt.date : new Date(); | |
if (+opt.minutes) d.setMinutes(d.getMinutes() + opt.minutes); | |
if (+opt.hours) d.setHours(d.getHours() + opt.hours); | |
if (+opt.days) d.setDate(d.getDate() + opt.days); | |
if (+opt.months) d.setMonth(d.getMonth() + opt.months); | |
if (+opt.years) d.setFullYear(d.getFullYear() + opt.years); | |
return d; | |
} |
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
alterDate({years: -6}); | |
// expected: | |
// six years before the current date | |
alterDate({days: 8}) | |
// expected: | |
// 8 days after the current date | |
alterDate({months: -2}); | |
// expected: | |
// two months before the current date | |
alterDate({ | |
date: new Date("2017/03/06"), | |
hours: -8 | |
}); | |
// expected: | |
// eight hours before the specified date (in CST) | |
var date = new Date("1995-12-17T03:24:59") // UTC | |
var offset = date.getTimezoneOffset() / 60; | |
var newDate = alterDate({date, hours: offset}); | |
newDate.toISOString(); | |
// expected (GMT +0): | |
// "1995-12-17T09:24:59.000Z" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment