set.cjs 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. "use strict";
  2. exports.set = set;
  3. var _index = require("./constructFrom.cjs");
  4. var _index2 = require("./setMonth.cjs");
  5. var _index3 = require("./toDate.cjs");
  6. /**
  7. * The {@link set} function options.
  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. function set(date, values, options) {
  44. let _date = (0, _index3.toDate)(date, options?.in);
  45. // Check if date is Invalid Date because Date.prototype.setFullYear ignores the value of Invalid Date
  46. if (isNaN(+_date)) return (0, _index.constructFrom)(options?.in || date, NaN);
  47. if (values.year != null) _date.setFullYear(values.year);
  48. if (values.month != null) _date = (0, _index2.setMonth)(_date, values.month);
  49. if (values.date != null) _date.setDate(values.date);
  50. if (values.hours != null) _date.setHours(values.hours);
  51. if (values.minutes != null) _date.setMinutes(values.minutes);
  52. if (values.seconds != null) _date.setSeconds(values.seconds);
  53. if (values.milliseconds != null) _date.setMilliseconds(values.milliseconds);
  54. return _date;
  55. }