替代使用Javascript转换UTC日期? [英] Alternative to casting UTC Date in Javascript?

查看:70
本文介绍了替代使用Javascript转换UTC日期?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望在JS中创建一个新的Date,但是将其转换为UTC时间。例如,假设 castAsUTC()产生以下预期效果:

I wish to create a new Date in JS, but have it be cast as UTC time. For example, suppose castAsUTC() produces the following desired effect:

var x = new Date('2019-01-01T00:00:00') // In local time (PST)
castAsUTC(x).toISOString(); // => '2019-01-01T00:00:00Z'
// x.toISOString() gives us '2019-01-01T08:00:00Z', which is undesired

当前,我的函数如下:

function castAsUTC(date) {
  return new Date(x.toLocaleString() + '+00:00');
}

是否有更清洁/更精细的方式来产生相同的效果?预先感谢!

Is there a cleaner/nicer way of producing the same effect? Thanks in advance!

编辑:更具体地说,我有兴趣更改日期的时区,而无需通过尽可能少的算术更改其实际值。因此,调用 .toISOString()会产生与本地时间相同的日期。

To be more specific, I'm interested in transforming the date's timezone, without changing its actual value with as little arithmetic as possible. So calling .toISOString() will produce the same date as it is in local time.

我正在使用 moment-timezone 库,但我似乎也无法使用该方法获得预期的效果。我肯定会接受使用Moment.js的答案

I am currently using the moment-timezone library, but I can't seem to get the desired effect using that, either. I would definitely accept an answer that uses Moment.js

推荐答案

您可以使用 utc 函数。然后只需使用 format 即可从中获取所需的特定输出。

You can switch a Moment instance to UTC using the utc function. Then just use format to get whatever the specific output you want from it.

这篇关于替代使用Javascript转换UTC日期?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆