Skip to content

Instantly share code, notes, and snippets.

@mmyoji
Last active August 25, 2023 10:06
Show Gist options
  • Save mmyoji/fd7e2f64f23e442137e671cfb0d42fb7 to your computer and use it in GitHub Desktop.
Save mmyoji/fd7e2f64f23e442137e671cfb0d42fb7 to your computer and use it in GitHub Desktop.
[Node.js, Deno] Modify Date function when you can't use Temporal
// see https://deno.land/std/datetime/constants.ts?source
const MILLISECOND = 1;
const SECOND = MILLISECOND * 1e3;
const MINUTE = SECOND * 60;
const HOUR = MINUTE * 60;
const DAY = HOUR * 24;
const WEEK = DAY * 7;
type Unit =
| "milliseconds"
| "seconds"
| "minutes"
| "hours"
| "days"
| "weeks"
| "months"
| "quarters"
| "years";
const unitToValue = {
milliseconds: MILLISECOND,
seconds: SECOND,
minutes: MINUTE,
hours: HOUR,
days: DAY,
weeks: WEEK,
} as const;
/**
* Returns modified new Date object in the given count and unit.
*
* @example
* ```ts
* import { modifyDate } from "./modify-date.ts";
*
* const date = new Date("2023-08-10T10:00:00.000Z");
*
* modifyDate(date, 10, "seconds");
* // output : new Date("2023-08-10T10:00:10.000Z");
*
* modifyDate(date, 60, "seconds");
* // output : new Date("2023-08-10T10:01:00.000Z");
*
* modifyDate(date, -1, "hours");
* // output : new Date("2023-08-10T09:00:00.000Z");
*
* modifyDate(date, 3, "months");
* // output : new Date("2023-11-10T10:00:00.000Z");
* ```
*/
export function modifyDate(date: Date, count: number, unit: Unit): Date {
switch (unit) {
case "months": {
return modifyMonth(date, count);
}
case "quarters": {
return modifyMonth(date, count * 4);
}
case "years": {
const d = structuredClone(date);
d.setFullYear(d.getFullYear() + count);
return d;
}
default: {
const v = unitToValue[unit];
if (!v) throw new Error(`unexpected unit is given: ${unit}`);
return new Date(date.getTime() + count * v);
}
}
}
function modifyMonth(date: Date, count: number) {
const d = structuredClone(date);
d.setMonth(d.getMonth() + count);
return d;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment