1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
/**
* Substract a duration from a date.
*
* @see https://stackoverflow.com/a/71574784/3997690
*/
export const subtractFromDate = (
date,
{ years, days, hours, minutes, seconds, milliseconds }: {
years?: number;
days?: number;
hours?: number;
minutes?: number;
seconds?: number;
milliseconds?: number;
} = {},
) => {
const millisecondsOffset = milliseconds ?? 0;
const secondsOffset = seconds ? 1000 * seconds : 0;
const minutesOffset = minutes ? 1000 * 60 * minutes : 0;
const hoursOffset = hours ? 1000 * 60 * 60 * hours : 0;
const daysOffset = days ? 1000 * 60 * 60 * 24 * days : 0;
const dateOffset = millisecondsOffset +
secondsOffset +
minutesOffset +
hoursOffset +
daysOffset;
let newDate = date;
if (years)
newDate = date.setFullYear(date.getFullYear() - years);
return new Date(newDate - dateOffset);
};
Val Town is a social website to write and deploy JavaScript.
Build APIs and schedule functions from your browser.
Comments
Nobody has commented on this val yet: be the first!
October 23, 2023