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