Skip to content

Instantly share code, notes, and snippets.

@NateScarlet
Last active November 19, 2020 03:50
Show Gist options
  • Save NateScarlet/6afb653af77522df00708c8a92fdff22 to your computer and use it in GitHub Desktop.
Save NateScarlet/6afb653af77522df00708c8a92fdff22 to your computer and use it in GitHub Desktop.
clone Date object with a optional offset and data override
/** 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