从字符串获取时区缩写

时间:2018-12-06 21:59:42

标签: javascript momentjs

我如何从字符串中获取时间和缩写的时区。我做错了什么?

const timestampString = 'Wed Dec 05 2018 22:00:00 GMT-0800 (Pacific Standard Time)';
const timezoneAbbreviation = moment.tz(timestampString).format('z'); // expecting PST, but result is UTC

2 个答案:

答案 0 :(得分:0)

该功能为deprecated in moment,只能通过class User << ActiveRecord::Base has_many :acknowledgements end class Event << ActiveRecord::Base has_many :acknowledgements has_many :tracks, through: event_track end class Acknowledgement << ActiveRecord::Base belongs_to :user belongs_to :event end class Track << ActiveRecord::Base has_many :event_tracks has_many :events, through: event_tracks end class EventTrack << ActiveRecord::Base belongs_to :event belongs_to :track end 使用,如下所示:

moment-timezone
const timestampString = 'Wed Dec 05 2018 22:00:00 GMT-0800 (Pacific Standard Time)';
const result = moment(new Date(timestampString)).tz('America/Los_Angeles').format('z')

console.log(result)

注意:您需要先使用有效日期实例化时刻,等等。

其背后的原因是,没有一种一致的方法可以尽可能read here的方式从本地Date对象<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/moment-timezone/0.5.23/moment-timezone-with-data.min.js"></script>获得时区缩写。

答案 1 :(得分:0)

对于使用 date-fns-tz 的任何人,您可以找到以下时区缩写

const { utcToZonedTime, format } = require('date-fns-tz')

const date = new Date('2018-09-01T16:01:36.386Z')
const zonedDate = utcToZonedTime(date, 'America/Toronto')

const pattern = 'zzz'
const timeZoneAbbr = format(zonedDate, pattern, { timeZone: 'America/Toronto' })

-> timeZoneAbbr : EDT

以上是documentation page

中给出的示例