1 | import { constructFrom } from "./constructFrom.js";
|
2 | import { subDays } from "./subDays.js";
|
3 | import { subMonths } from "./subMonths.js";
|
4 |
|
5 | /**
|
6 | * The {@link sub} function options.
|
7 | */
|
8 |
|
9 | /**
|
10 | * @name sub
|
11 | * @category Common Helpers
|
12 | * @summary Subtract the specified years, months, weeks, days, hours, minutes and seconds from the given date.
|
13 | *
|
14 | * @description
|
15 | * Subtract the specified years, months, weeks, days, hours, minutes and seconds from the given date.
|
16 | *
|
17 | * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).
|
18 | * @typeParam ResultDate - The result `Date` type, it is the type returned from the context function if it is passed, or inferred from the arguments.
|
19 | *
|
20 | * @param date - The date to be changed
|
21 | * @param duration - The object with years, months, weeks, days, hours, minutes and seconds to be subtracted
|
22 | * @param options - An object with options
|
23 | *
|
24 | * | Key | Description |
|
25 | * |---------|------------------------------------|
|
26 | * | years | Amount of years to be subtracted |
|
27 | * | months | Amount of months to be subtracted |
|
28 | * | weeks | Amount of weeks to be subtracted |
|
29 | * | days | Amount of days to be subtracted |
|
30 | * | hours | Amount of hours to be subtracted |
|
31 | * | minutes | Amount of minutes to be subtracted |
|
32 | * | seconds | Amount of seconds to be subtracted |
|
33 | *
|
34 | * All values default to 0
|
35 | *
|
36 | * @returns The new date with the seconds subtracted
|
37 | *
|
38 | * @example
|
39 | * // Subtract the following duration from 15 June 2017 15:29:20
|
40 | * const result = sub(new Date(2017, 5, 15, 15, 29, 20), {
|
41 | * years: 2,
|
42 | * months: 9,
|
43 | * weeks: 1,
|
44 | * days: 7,
|
45 | * hours: 5,
|
46 | * minutes: 9,
|
47 | * seconds: 30
|
48 | * })
|
49 | * //=> Mon Sep 1 2014 10:19:50
|
50 | */
|
51 | export function sub(date, duration, options) {
|
52 | const {
|
53 | years = 0,
|
54 | months = 0,
|
55 | weeks = 0,
|
56 | days = 0,
|
57 | hours = 0,
|
58 | minutes = 0,
|
59 | seconds = 0,
|
60 | } = duration;
|
61 |
|
62 | const withoutMonths = subMonths(date, months + years * 12, options);
|
63 | const withoutDays = subDays(withoutMonths, days + weeks * 7, options);
|
64 |
|
65 | const minutesToSub = minutes + hours * 60;
|
66 | const secondsToSub = seconds + minutesToSub * 60;
|
67 | const msToSub = secondsToSub * 1000;
|
68 |
|
69 | return constructFrom(options?.in || date, +withoutDays - msToSub);
|
70 | }
|
71 |
|
72 | // Fallback for modularized imports:
|
73 | export default sub;
|