set.mjs 2.2 KB

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