transpose.js 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. import { constructFrom } from "./constructFrom.js";
  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 InputDate - The input `Date` type derived from the passed argument.
  13. * @typeParam ResultDate - The result `Date` type derived from the passed constructor.
  14. *
  15. * @param date - 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(date, constructor) {
  31. const date_ = isConstructor(constructor)
  32. ? new constructor(0)
  33. : constructFrom(constructor, 0);
  34. date_.setFullYear(date.getFullYear(), date.getMonth(), date.getDate());
  35. date_.setHours(
  36. date.getHours(),
  37. date.getMinutes(),
  38. date.getSeconds(),
  39. date.getMilliseconds(),
  40. );
  41. return date_;
  42. }
  43. function isConstructor(constructor) {
  44. return (
  45. typeof constructor === "function" &&
  46. constructor.prototype?.constructor === constructor
  47. );
  48. }
  49. // Fallback for modularized imports:
  50. export default transpose;