我想要一个 UTC 时间的日期时间对象,而不是 UTC 日期时间字符串。
以下代码帮助我获取字符串形式的 UTC 时间:
moment.parseZone(new Date()).utc().format()
上面代码的输出是:
"2019-01-14T12:43:23Z"
上面是一个字符串,我不想要它。 我想要的是一个日期时间对象。 这是我将日期时间字符串转换为日期时间对象的方法:
new Date(moment.parseZone(new Date()).utc().format())
不幸的是,上面的代码再次将输出转换为本地时间,其示例如下所示:
Mon Jan 14 2019 18:10:54 GMT+0530 (India Standard Time)
我们如何阻止 UTC 日期时间对象转换为本地日期时间?
Edit-01:如何使用 UTC 时间的日期时间对象执行计算?
Edit-02:功能说明:
有些人处于不同的时区。我们知道UTC时差。我想建立一个每个人本地时间的表。
示例:我的时区是 +5:30 UTC(我的时间目前是 01/14/2019 9:00pm),来自旧金山的人的时区是 -8:00 UTC(他/她的时间目前是 01/14/2019 7:30am)。
目前,我想做的是将时差(-8:00 UTC)添加到UTC时间以找到旧金山人的本地时间。这不起作用,因为当我将 UTC 日期时间字符串转换为日期对象时,它将转换为本地时间。
最佳答案
<强> Javascript dates have no timezone! 这是您用于序列化的“静态”方法,偷偷地应用了一个方法。让您担心的输出是控制台中使用的 Date.toString() 的标准输出。基础日期可能没问题(您刚刚从无到有创建它,因此不存在可能的反序列化问题)。您只需在序列化时指定 UTC 方法即可。尝试 Date.toISOString()
或 Date.toLocaleDateString({},{timeZone:'UTC'})
在功能解释后进行编辑...
好的,这里有一些您可以做的事情。肯尼迪于 1963 年 11 月 22 日中午 12:30 中部标准时间被刺杀
// create a date object to represent this moment...
const byeByeKennedy = new Date("1963-11-22T12:30:00-06:00");
// this is a date object, representing a moment. We used a
// timezone for it's creation, but now it has no notion of timezone.
// if you want to know what time it was IN THE TIMEZONE OF THE USER,
// just do toString(), or leave timezone blank. Formatting in the
// timezone of the user is always the default in javascript.
// This does not mean that the Date intrinsically has a timezone though!
console.log('My local time when kennedy was killed... '
+ byeByeKennedy.toString());
// If we want to format this date with it's "original" timezone, we need
// to store the timezone separately, then use it again to serialize...
console.log('Local time in Dallas when Kennedy was killed... '
+ byeByeKennedy.toLocaleString({},{timeZone:"America/Chicago"}))
// If you, sitting in India, need to know what time it was for
// your user in San Francisco when kennedy
// was killed, you need to supply the timezone of San Francisco...
console.log('Local time in San Francisco when Kennedy was killed... '
+ byeByeKennedy.toLocaleString({},{timeZone:"America/Los_Angeles"}))
// If you want to serialize this date, for example to send it to a server, use ISO...
console.log('Use ISO for serializing/sending... '
+ byeByeKennedy.toISOString());
// OR IF YOU JUST WANT TO KNOW WHAT TIME IT IS IN SAN FRANCISCO...
console.log('SAN FRANCISCO TIME NOW... '
+ new Date().toLocaleString({},{timeZone:"America/Los_Angeles"}))
如果确实有必要,您可以直接将时区偏移量添加到日期,然后指定 UTC 对其进行格式化,但这是一个糟糕的主意,因为您需要管理夏令时和其他微妙之处。请不要这样做。最好在创建时真正清楚时区,然后在格式化时就清楚了。
关于javascript - 我们如何停止将 UTC 日期时间对象转换为本地日期时间?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54181898/