set.js 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. import { constructFrom } from "./constructFrom.js";
  2. import { setMonth } from "./setMonth.js";
  3. import { toDate } from "./toDate.js";
  4. /**
  5. * The {@link set} function options.
  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. * @typeParam ResultDate - The result `Date` type, it is the type returned from the context function if it is passed, or inferred from the arguments.
  24. *
  25. * @param date - The date to be changed
  26. * @param values - The date values to be set
  27. * @param options - The options
  28. *
  29. * @returns The new date with options set
  30. *
  31. * @example
  32. * // Transform 1 September 2014 into 20 October 2015 in a single line:
  33. * const result = set(new Date(2014, 8, 20), { year: 2015, month: 9, date: 20 })
  34. * //=> Tue Oct 20 2015 00:00:00
  35. *
  36. * @example
  37. * // Set 12 PM to 1 September 2014 01:23:45 to 1 September 2014 12:00:00:
  38. * const result = set(new Date(2014, 8, 1, 1, 23, 45), { hours: 12 })
  39. * //=> Mon Sep 01 2014 12:23:45
  40. */
  41. export function set(date, values, options) {
  42. let _date = toDate(date, options?.in);
  43. // Check if date is Invalid Date because Date.prototype.setFullYear ignores the value of Invalid Date
  44. if (isNaN(+_date)) return constructFrom(options?.in || date, NaN);
  45. if (values.year != null) _date.setFullYear(values.year);
  46. if (values.month != null) _date = setMonth(_date, values.month);
  47. if (values.date != null) _date.setDate(values.date);
  48. if (values.hours != null) _date.setHours(values.hours);
  49. if (values.minutes != null) _date.setMinutes(values.minutes);
  50. if (values.seconds != null) _date.setSeconds(values.seconds);
  51. if (values.milliseconds != null) _date.setMilliseconds(values.milliseconds);
  52. return _date;
  53. }
  54. // Fallback for modularized imports:
  55. export default set;