1 | ;
|
2 | exports.add = add;
|
3 | var _index = require("./addDays.js");
|
4 | var _index2 = require("./addMonths.js");
|
5 | var _index3 = require("./constructFrom.js");
|
6 | var _index4 = require("./toDate.js");
|
7 |
|
8 | /**
|
9 | * @name add
|
10 | * @category Common Helpers
|
11 | * @summary Add the specified years, months, weeks, days, hours, minutes and seconds to the given date.
|
12 | *
|
13 | * @description
|
14 | * Add the specified years, months, weeks, days, hours, minutes and seconds to the given date.
|
15 | *
|
16 | * @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).
|
17 | *
|
18 | * @param date - The date to be changed
|
19 | * @param duration - The object with years, months, weeks, days, hours, minutes and seconds to be added.
|
20 | *
|
21 | * | Key | Description |
|
22 | * |----------------|------------------------------------|
|
23 | * | years | Amount of years to be added |
|
24 | * | months | Amount of months to be added |
|
25 | * | weeks | Amount of weeks to be added |
|
26 | * | days | Amount of days to be added |
|
27 | * | hours | Amount of hours to be added |
|
28 | * | minutes | Amount of minutes to be added |
|
29 | * | seconds | Amount of seconds to be added |
|
30 | *
|
31 | * All values default to 0
|
32 | *
|
33 | * @returns The new date with the seconds added
|
34 | *
|
35 | * @example
|
36 | * // Add the following duration to 1 September 2014, 10:19:50
|
37 | * const result = add(new Date(2014, 8, 1, 10, 19, 50), {
|
38 | * years: 2,
|
39 | * months: 9,
|
40 | * weeks: 1,
|
41 | * days: 7,
|
42 | * hours: 5,\\-7
|
43 | * minutes: 9,
|
44 | * seconds: 30,
|
45 | * })
|
46 | * //=> Thu Jun 15 2017 15:29:20
|
47 | */
|
48 | function add(date, duration) {
|
49 | const {
|
50 | years = 0,
|
51 | months = 0,
|
52 | weeks = 0,
|
53 | days = 0,
|
54 | hours = 0,
|
55 | minutes = 0,
|
56 | seconds = 0,
|
57 | } = duration;
|
58 |
|
59 | // Add years and months
|
60 | const _date = (0, _index4.toDate)(date);
|
61 | const dateWithMonths =
|
62 | months || years
|
63 | ? (0, _index2.addMonths)(_date, months + years * 12)
|
64 | : _date;
|
65 |
|
66 | // Add weeks and days
|
67 | const dateWithDays =
|
68 | days || weeks
|
69 | ? (0, _index.addDays)(dateWithMonths, days + weeks * 7)
|
70 | : dateWithMonths;
|
71 |
|
72 | // Add days, hours, minutes and seconds
|
73 | const minutesToAdd = minutes + hours * 60;
|
74 | const secondsToAdd = seconds + minutesToAdd * 60;
|
75 | const msToAdd = secondsToAdd * 1000;
|
76 | const finalDate = (0, _index3.constructFrom)(
|
77 | date,
|
78 | dateWithDays.getTime() + msToAdd,
|
79 | );
|
80 |
|
81 | return finalDate;
|
82 | }
|