transpose.cjs 1.6 KB

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