简体   繁体   中英

JavaScript - Compute UTC Value With Separate Date and Time Values in Specific Timezone

I am working with an API that returns the date and time of an event separately. The date is always stored in YYYY-MM-DD format and the time is always stored in HH:MM format. The application is local to a geographic area on the US East Coast and the datetime stamp that the separate date and time values combine to convey will always be in EST.

Using the date and the time values that the API gives me, I need to create a UNIX time value. I can hard code the offset between EST and UTC using the following:

new Date(dateValue + 'T' + timeValue + '-04:00').getTime() / 1000

But the above doesn't take into account daylight savings and I'll need to update the hardcode -04:00 value with -05:00 during every daylight savings change.

I can compute the UTC value using:

new Date(dateValue + ' ' + timeValue + ' EST').getTime() / 1000

But this does not work for mobile Safari since its JS implementation of Date() does not recognize date strings in 2019-11-21 05:00 EST format.

How would I compute the UTC value here that is both daylight savings time aware and compatible on all modern browsers?

I would prefer a solution that does not require a 3rd party library.

Well, you really don't want to get into handling DST yourself, so I agree with adding 'EST' to the date string and then using the built-in Date parser. Too bad about Safari.

You prefer to avoid a library, but how about a gist with a single js file that "Enhances Date.parse to support ES5 ISO-8601 strings in all environments" (with a loose definition of ISO date string)?

https://github.com/csnover/js-iso8601/tree/lax

You can consider using Intl.DateTimeFormat as mentioned in this answer. This handles timezones and daylight savings as well which I assume is what need:

 const options = { year: '2-digit', month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit', second: '2-digit', timeZone: 'Australia/Brisbane', timeZoneName: 'short' }, formater = new Intl.DateTimeFormat('en-US', options), startingDate = new Date('2012-04-10 10:10:30 -04:00'); const dateInNewTimezone = formater.format(startingDate); console.log(startingDate.toLocaleString()); console.log(dateInNewTimezone);

Please note the following is shown at my end:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM