【问题标题】:javascript parsing the date time as specified timezonejavascript将日期时间解析为指定时区
【发布时间】:2020-03-04 16:09:43
【问题描述】:

我正在使用 boomi 中间件,所以不能使用像 moment js 这样的库,它有我可以使用的解决方案,如下所示:

function toTimeZone(time, zone) {
    var format = 'YYYY/MM/DD HH:mm:ss ZZ';
    return moment(time, format).tz(zone).format(format);
}

我会收到的

  • 中间件中的日期为“yyyy-MM-dd HH:mm:ss”
  • 日期不是 UTC。根据发起请求,我知道该日期的时区,可能是 America/New_York (EST) 或 America/Los_Angeles (PST) 等

如何将此日期时间转换为 UTC?

这就是我想要做的事情

var myDate = new Date("2020-02-27 11:19:00").toDateString("en-US", {timeZone: "America/Los_Angeles"});
document.write(myDate + '<br>'); //.toDateString() toLocaleString
myDate = new Date(myDate);
document.write(myDate.getFullYear() + "-" + (myDate.getMonth() + 1) + "-" + myDate.getDate() + 
                    " " + myDate.getHours() + ":" + myDate.getMinutes() + ":" + myDate.getSeconds());

这将导致以下结果。我已经失去了我的时间。

Thu Feb 27 2020
2020-2-27 0:0:0

【问题讨论】:

  • 您从哪里获得请求中的时区?那套在哪里?
  • 我真的很想尝试一下,因为这并不容易自己做到
  • 根据站点,我们知道它的时区。我不能在 BOOMI 上使用 moment.js 等。
  • 花了一些时间后,我将采用不同的解决方案,我现在正在处理 C# 微服务中的日期,其中获取偏移量要简单得多。

标签: javascript


【解决方案1】:

是的,你当然浪费了时间。那是因为你告诉它走开!

> (new Date()).toDateString()
'Wed Mar 04 2020'

你可以使用

> (new Date()).toLocaleString()
'3/4/2020, 10:19:06 AM'

但是,正如您在 cmets 中所述,您还需要反转偏移量。

我相信这行得通:

const toUTC = (dateString, timezoneName) => {
  offset = new Date((new Date(0)).toLocaleString("en-US", {timeZone: timezoneName})); // from local time to time-zone time
  return new Date((new Date(dateString)).getTime() - offset.getTime())
}

例如:

> toUTC('2020-02-27 11:19:00', 'America/Chicago')
2020-02-27T17:19:00.000Z
> toUTC('2020-02-27 11:19:00', 'America/New_York')
2020-02-27T16:19:00.000Z
> toUTC('2020-02-27 11:19:00', 'Europe/Berlin')
2020-02-27T10:19:00.000Z
> toUTC('2020-02-27 11:19:00', 'GMT')
2020-02-27T11:19:00.000Z

【讨论】:

  • 不会 toLocaleString 将区域更改为运行脚本的机器区域
  • var myDate = new Date("2020-02-27 11:19:00").toLocaleString("en-US", {timeZone: "America/Los_Angeles"}); 导致2/27/2020, 8:19:00 AM 2020-2-27 8:19:0。它正在转换为8:19AM
  • 我将采用不同的解决方案,我现在正在处理 C# 微服务中的日期,其中获取偏移量要简单得多。
  • 你是对的;这是一个很好的问题。通过首先计算偏移量必须是可能的。仍在努力。
  • 那是因为你的 document.write(myDate) 是“天真的”,它不知道你想要一个 UTC 时间。日期对象本身存储时区,因此一旦您有了正确的日期,您就可以将它打印到您想要的任何时区。在你的情况下,我认为你想要document.write(myDate.toUTCString())
【解决方案2】:

我会收到的

the date in the middleware as "yyyy-MM-dd HH:mm:ss"
the date is not UTC. Depending upon the originating request, i know the time zone of this date which could be America/New_York (EST)

或美国/洛杉矶 (PST) 等

let datetime = new Date("2020-02-27 11:19:00").toISOString().split('-').join('/')

我的控制台中的示例:

new Date("2020-02-27 11:19:00").toISOString().split('-').join('/')
"2020/02/27T10:19:00.000Z"

【讨论】:

  • 这是不正确的。我的日期时间属于特定时区的网站。
  • 就我而言,日期时间可能属于东部、太平洋、山区。它可以是这些时区中的任何一个。
猜你喜欢
  • 2013-03-27
  • 2013-09-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-09-12
  • 2017-02-26
相关资源
最近更新 更多