简体   繁体   中英

Convert a date with GMT to a human readable time zone in an angular app using TS or JS

I have a date value returned from an api call. This date includes a value like GMT-7. How best to turn that into a human readable time zone like 'PST' or 'Pacific Standard Time' so final string will be December 31, 2021 at 4:00:00 PM (PST) and not GMT-7

The GMT/UTC minus 7 hours offset is used in the Pacific Time Zone during Daylight Saving Time (DST) period and in the Mountain Time Zone during the Standard Time period, when no DST is applied.

Moment.js is not an option because of it's file size and deprecation.

Ok further clarification from my product owner: the time can be returned reflecting the time in the users time zone. So if it is 7pm EST time in the original date and user is in Pacific Time PST they will see 3pm PST to reflect same time according to their zone.

You may try to use new Date().toLocaleString(......) function.

There is no standard for timezone names or abbreviations, and sometimes with either timeZoneName short or long the format* methods will return something like GMT+07:00 or UTC+07:00 depending on the browser default language, even if "en" or "en-US" or whatever is specified.

However, you can use Intl.DateTimeFormat with formatToParts and timeZoneName:'long' then abbreviate it yourself where the timeZoneName value doesn't contain numbers.

This won't fix cases where the implementation doesn't have a name for the timezone, but for more common timezones like those in Europe and the US with language "en" it should be OK, eg

 function formatDate(date) { let {year, month, day, hour, minute, second, timeZoneName} = new Intl.DateTimeFormat("en", { year: 'numeric', month: 'long', day: 'numeric', hour: '2-digit', minute: '2-digit', second: '2-digit', hour12: false, timeZone: 'America/Los_Angeles', timeZoneName:'long' }).formatToParts(date).reduce((acc, part) => { acc[part.type] = part.value; return acc; }, Object.create(null)); // If timezone doesn't contain numbers, abbreviate // Otherwise, return the name as given by formatToParts let tz = /\d/.test(timeZoneName)? timeZoneName: timeZoneName.replace(/[^AZ]/g,''); return `${month} ${day}, ${year} ${hour}:${minute}:${second} ${tz}` } console.log(formatDate(new Date())); console.log(formatDate(new Date(2021,0,1))); console.log(formatDate(new Date(2021,5,1)));

let date = api date

new Date(Date.UTC(date.getFullYear(), date.getMonth(), date.getDate(), date.getHours(), date.getMinutes(), date.getSeconds()))

converts to gmt 00:00

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