transpose.mjs 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. import { constructFrom } from "./constructFrom.mjs";
  2. /**
  3. * @name transpose
  4. * @category Generic Helpers
  5. * @summary Transpose the date to the given constructor.
  6. *
  7. * @description
  8. * The function transposes the date to the given constructor. It helps you
  9. * to transpose the date in the system time zone to say `UTCDate` or any other
  10. * date extension.
  11. *
  12. * @typeParam DateInputType - The input `Date` type derived from the passed argument.
  13. * @typeParam DateOutputType - The output `Date` type derived from the passed constructor.
  14. *
  15. * @param fromDate - The date to use values from
  16. * @param constructor - The date constructor to use
  17. *
  18. * @returns Date transposed to the given constructor
  19. *
  20. * @example
  21. * // Create July 10, 2022 00:00 in locale time zone
  22. * const date = new Date(2022, 6, 10)
  23. * //=> 'Sun Jul 10 2022 00:00:00 GMT+0800 (Singapore Standard Time)'
  24. *
  25. * @example
  26. * // Transpose the date to July 10, 2022 00:00 in UTC
  27. * transpose(date, UTCDate)
  28. * //=> 'Sun Jul 10 2022 00:00:00 GMT+0000 (Coordinated Universal Time)'
  29. */
  30. export function transpose(fromDate, constructor) {
  31. const date =
  32. constructor instanceof Date
  33. ? constructFrom(constructor, 0)
  34. : new constructor(0);
  35. date.setFullYear(
  36. fromDate.getFullYear(),
  37. fromDate.getMonth(),
  38. fromDate.getDate(),
  39. );
  40. date.setHours(
  41. fromDate.getHours(),
  42. fromDate.getMinutes(),
  43. fromDate.getSeconds(),
  44. fromDate.getMilliseconds(),
  45. );
  46. return date;
  47. }
  48. // Fallback for modularized imports:
  49. export default transpose;