Last active
November 19, 2020 03:50
-
-
Save NateScarlet/6afb653af77522df00708c8a92fdff22 to your computer and use it in GitHub Desktop.
clone Date object with a optional offset and data override
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
/** clone Date object with a optional offset and data override */ | |
export default function cloneDate( | |
date: Date, | |
offset?: { | |
year?: number; | |
month?: number; | |
day?: number; | |
hour?: number; | |
minute?: number; | |
seconds?: number; | |
milliseconds?: number; | |
}, | |
set?: { | |
year?: number; | |
month?: number; | |
day?: number; | |
hour?: number; | |
minute?: number; | |
seconds?: number; | |
milliseconds?: number; | |
} | |
): Date { | |
const ret = new Date(date); | |
if (offset?.year) { | |
ret.setFullYear(date.getFullYear() + offset.year); | |
} | |
if (offset?.month) { | |
ret.setMonth(date.getMonth() + offset.month); | |
} | |
if (offset?.day) { | |
ret.setDate(date.getDate() + offset.day); | |
} | |
if (offset?.hour) { | |
ret.setHours(date.getHours() + offset.hour); | |
} | |
if (offset?.minute) { | |
ret.setMinutes(date.getMinutes() + offset.minute); | |
} | |
if (offset?.seconds) { | |
ret.setSeconds(date.getSeconds() + offset.seconds); | |
} | |
if (offset?.milliseconds) { | |
ret.setMilliseconds(date.getMilliseconds() + offset.milliseconds); | |
} | |
if (set?.year != null) { | |
ret.setFullYear(set.year); | |
} | |
if (set?.month != null) { | |
ret.setMonth(set.month); | |
} | |
if (set?.day != null) { | |
ret.setDate(set.day); | |
} | |
if (set?.hour != null) { | |
ret.setHours(set.hour); | |
} | |
if (set?.minute != null) { | |
ret.setMinutes(set.minute); | |
} | |
if (set?.seconds != null) { | |
ret.setSeconds(set.seconds); | |
} | |
if (set?.milliseconds != null) { | |
ret.setMilliseconds(set.milliseconds); | |
} | |
return ret; | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment