UNPKG

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