|
1 | | -export function utcOffset(isoString: string, timezone = 'America/New_York') { |
| 1 | +export function utcOffset(isoString: string, timeZone = 'America/new_york') { |
2 | 2 | console.log('conversion:input', isoString); |
3 | | - const originalDate = new Date( |
4 | | - new Date(isoString).toLocaleString('en-US', { |
5 | | - timeZone: timezone, |
6 | | - }) |
7 | | - ); |
8 | | - const utcDate = new Date( |
9 | | - new Date(isoString).toLocaleString('en-US', { |
10 | | - timeZone: 'UTC', |
11 | | - }) |
12 | | - ); |
13 | | - |
14 | | - // // Milliseconds from original Date |
15 | | - const offset = originalDate.getTime() - utcDate.getTime(); |
16 | | - const output = new Date(Date.parse(originalDate.toISOString()) + offset) |
| 3 | + const isoStringDate = new Date(isoString); |
| 4 | + const offset = getOffset(timeZone, isoStringDate); |
| 5 | + console.log('conversion:offsethours', offset / 60 / 60 / 1000); |
| 6 | + const output = new Date(Date.parse(isoStringDate.toISOString()) + offset) |
17 | 7 | .toISOString() |
18 | 8 | .replace('Z', ''); |
19 | 9 | console.log('conversion:output', output); |
20 | 10 | return output; |
21 | 11 | } |
22 | 12 |
|
| 13 | +const getOffset = (timeZone = 'UTC', date = new Date()) => { |
| 14 | + const utcDate = new Date(date.toLocaleString('en-US', { timeZone: 'UTC' })); |
| 15 | + const tzDate = new Date(date.toLocaleString('en-US', { timeZone })); |
| 16 | + return tzDate.getTime() - utcDate.getTime(); |
| 17 | +}; |
| 18 | + |
23 | 19 | const calendlyDate = '2022-01-26T14:00:00.000000Z'; |
24 | 20 | console.log('hardcoded:calendlyDate', calendlyDate); |
25 | 21 | console.log('hardcoded:fromFunc', utcOffset(calendlyDate)); |
26 | | -console.log('hardcoded:shouldMatch', '2022-01-26T09:00:00.000000-05:00'); |
27 | | -console.log( |
28 | | - 'hardcoded:shouldMatchLocale', |
29 | | - new Date('2022-01-26T09:00:00.000000-05:00').toLocaleString('en-US', { |
30 | | - timeZone: 'America/New_York', |
31 | | - }) |
32 | | -); |
| 22 | +console.log('hardcoded:shouldMatch', '2022-01-26T09:00:00.000'); |
0 commit comments