1 | import { constructFrom } from "./constructFrom.js";
|
2 | import { setMonth } from "./setMonth.js";
|
3 | import { toDate } from "./toDate.js";
|
4 |
|
5 | /**
|
6 | * The {@link set} function options.
|
7 | */
|
8 |
|
9 | /**
|
10 | * @name set
|
11 | * @category Common Helpers
|
12 | * @summary Set date values to a given date.
|
13 | *
|
14 | * @description
|
15 | * Set date values to a given date.
|
16 | *
|
17 | * Sets time values to date from object `values`.
|
18 | * A value is not set if it is undefined or null or doesn't exist in `values`.
|
19 | *
|
20 | * Note about bundle size: `set` does not internally use `setX` functions from date-fns but instead opts
|
21 | * to use native `Date#setX` methods. If you use this function, you may not want to include the
|
22 | * other `setX` functions that date-fns provides if you are concerned about the bundle size.
|
23 | *
|
24 | * @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).
|
25 | * @typeParam ResultDate - The result `Date` type, it is the type returned from the context function if it is passed, or inferred from the arguments.
|
26 | *
|
27 | * @param date - The date to be changed
|
28 | * @param values - The date values to be set
|
29 | * @param options - The options
|
30 | *
|
31 | * @returns The new date with options set
|
32 | *
|
33 | * @example
|
34 | * // Transform 1 September 2014 into 20 October 2015 in a single line:
|
35 | * const result = set(new Date(2014, 8, 20), { year: 2015, month: 9, date: 20 })
|
36 | * //=> Tue Oct 20 2015 00:00:00
|
37 | *
|
38 | * @example
|
39 | * // Set 12 PM to 1 September 2014 01:23:45 to 1 September 2014 12:00:00:
|
40 | * const result = set(new Date(2014, 8, 1, 1, 23, 45), { hours: 12 })
|
41 | * //=> Mon Sep 01 2014 12:23:45
|
42 | */
|
43 | export function set(date, values, options) {
|
44 | let _date = toDate(date, options?.in);
|
45 |
|
46 | // Check if date is Invalid Date because Date.prototype.setFullYear ignores the value of Invalid Date
|
47 | if (isNaN(+_date)) return constructFrom(options?.in || date, NaN);
|
48 |
|
49 | if (values.year != null) _date.setFullYear(values.year);
|
50 | if (values.month != null) _date = setMonth(_date, values.month);
|
51 | if (values.date != null) _date.setDate(values.date);
|
52 | if (values.hours != null) _date.setHours(values.hours);
|
53 | if (values.minutes != null) _date.setMinutes(values.minutes);
|
54 | if (values.seconds != null) _date.setSeconds(values.seconds);
|
55 | if (values.milliseconds != null) _date.setMilliseconds(values.milliseconds);
|
56 |
|
57 | return _date;
|
58 | }
|
59 |
|
60 | // Fallback for modularized imports:
|
61 | export default set;
|