Skip to content

Instantly share code, notes, and snippets.

@aarongeorge
Last active April 6, 2020 00:42
Show Gist options
  • Save aarongeorge/80b66cf141261d70816b4b49ccf02578 to your computer and use it in GitHub Desktop.
Save aarongeorge/80b66cf141261d70816b4b49ccf02578 to your computer and use it in GitHub Desktop.
Modify JavaScript Date - Add and/or Subtract Years, Months, Weeks, Days, Hours, Minutes, Seconds and Milliseconds
const modifyDate = (date: Date, options: {[key in 'years' | 'months' | 'weeks' | 'days' | 'hours' | 'minutes' | 'seconds' | 'milliseconds']?: number} = {}) => {
const modifiedDate = new Date(date)
if (options.years) modifiedDate.setFullYear(modifiedDate.getFullYear() + options.years)
if (options.months) modifiedDate.setMonth(modifiedDate.getMonth() + options.months)
if (options.weeks) modifiedDate.setDate(modifiedDate.getDate() + options.weeks * 7)
if (options.days) modifiedDate.setDate(modifiedDate.getDate() + options.days)
if (options.hours) modifiedDate.setHours(modifiedDate.getHours() + options.hours)
if (options.minutes) modifiedDate.setMinutes(modifiedDate.getMinutes() + options.minutes)
if (options.seconds) modifiedDate.setSeconds(modifiedDate.getSeconds() + options.seconds)
if (options.milliseconds) modifiedDate.setMilliseconds(modifiedDate.getMilliseconds() + options.milliseconds)
return modifiedDate
}
// Store reference to date we want to modify
const originalDate = new Date(2000, 0, 1, 0, 0, 0, 0) // Sat Jan 01 2000 00:00:00
// Add 1 year
modifyDate(originalDate, {years: 1}) // Mon Jan 10 2001 00:00:00
// Subtract 1 hour
modifyDate(originalDate, {hours: -1}) // Fri Dec 31 1999 23:00:00
// Add 2 weeks and 3 days
modifyDate(originalDate, {weeks: 2, days: 3}) // Tue Jan 18 2001 00:00:00
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment