首页 文章

UTC IANA时区位置的时间

提问于
浏览
3

我在webapp here中看到了处理时间的精彩摘要 . 但是,它没有明确解决以下情况 . 我希望能够根据UTC位置的日期时间(iana时区位置 - America / New_York)获取Web应用程序的本地时间 .

我正在寻找一个进行以下计算的库 . 如果它在Javascript中本地工作,那也符合我的目的 .

从服务器,检索以下信息

{
  dateTime: "2002-10-27T15:04:05Z" # Time in UTC, no TimeZone info
  userTimeZone: "America/New_York" # based on current user location
}

问题在于,考虑到夏令时抵消,我无法找到将其转换为位置(纽约)的时间的方法 .

我不确定在数据库中保存时区偏移可以解决问题,因为我的用户可能来自跨区域并且可能会查看相同的数据 . 例如,事件发生在属于Estern区域(EST / EDT)的位置,但太平洋区域的用户可以根据其位置查询数据(上午8点 - 下午5点“America / Los_Angeles” - PST / PDT) .

我看了Moment.js,但找不到解决方案 .

To summarize, I need a way to get the local time at a specific location(considering daylight savings offset) in web browser, from an input of date time at UTC + IANA location.

3 回答

  • 3

    Original Answer

    MomentJS是一个优秀的库,但它专注于解析 . 你需要TimezoneJS,它在javascript中实现了Olson数据库 .

    您的用例是文档中描述的第一个用例之一 .

    Updated Answer

    有多个库可用于在JavaScript中进行时区转换,as listed here . 在最初询问这个问题时,我只知道TimezoneJS .

    既然你问过moment.js,你应该使用moment-timezone插件 . (当您最初提出问题时,这不可用 . )

    var x = // your object as written in the question
    
    var m = moment(x.dateTime).tz(x.userTimeZone);
    
    var s = m.format(); // or whatever you want to do
    
  • 2

    MomentJS的优秀人员创建了另一个名为Moment Timezone的库 . 我认为this正是您所寻找的 . 特别:

    var zone = moment.tz.zone('America/New_York');
    zone.parse(Date.UTC(2012, 2, 19, 8, 30)); // 240
    
  • 2

    您可以在没有使用 toLocaleDateString 方法的库的情况下实现此目的:

    // prints 'Sun, Oct 27, 2002, 10:04 AM EST'
    new Date('2002-10-27T15:04:05Z')
    .toLocaleDateString('en-US', {
      timeZone:'America/New_York',
      timeZoneName: 'short',
      minute: 'numeric',
      hour: 'numeric',
      weekday: 'short',
      day: 'numeric',
      year: 'numeric',
      month: 'short',
    });
    

    Intl.DateTimeFormatvery similar方式工作 .

    在Chrome,Firefox和Safari(OSX)上测试过 . 请注意according to MDN,timezone属性只需要支持'UTC',并且可能无法在所有浏览器中实现完整的IANA数据库 . 您可以通过其他设置支持更新此答案 .

相关问题