javascript - 如何在不创建新的时刻对象的情况下获得所需时区的小时和分钟?

标签 javascript timezone momentjs

我必须以这种格式在网页上显示一个字符串:16:00 HH:mm

我正在使用 moment 对象来表示日期/时间和时区。

var day = moment().tz('GMT');
day.hours(16).minutes(0).seconds(0).milliseconds(0);

现在是格林威治标准时间 16:00。

我想在我的网页上更改时区,然后收集小时和分钟。

如果我创建一个新的时刻对象

var day2 = moment().tz('PST); //this is 8 AM since gmt was 16
console.log(day2.get('hours'));

是 16 不是 8!

并尝试获取他们在 GMT 而非 PST 中的小时和分钟。

如何在 PST 中获取它?我必须一直包裹它吗?

最佳答案

// initialize a new moment object to midnight UTC of the current UTC day
var m1 = moment.utc().startOf('day'); 

// set the time you desire, in UTC
m1.hours(16).minutes(0);

// clone the existing moment object to create a new one
var m2 = moment(m1);   // OR  var m2 = m1.clone();   (both do the same thing)

// set the time zone of the new object
m2.tz('America/Los_Angeles');

// format the output for display
console.log(m2.format('HH:mm'));

Working jsFiddle here.

如果你不能让它工作,那么你没有正确加载时刻、时刻-时区和所需的时区数据。对于数据,您需要使用您关心的区域的区域数据调用 moment.tz.add,或者您需要使用 moment-timezone-with-data 文件之一网站。

在 fiddle 中,您可以通过展开“外部资源”部分来查看我正在加载的时刻文件。

fiddle resources

关于javascript - 如何在不创建新的时刻对象的情况下获得所需时区的小时和分钟?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34324208/

相关文章:

javascript - express.js 压缩中间件不起作用

javascript - 如何在javascript中编写html代码?

mysql - 由于时区,apt-get 升级在 mariadb-server 上总是失败

javascript - 为什么 moment js 给出的毫秒数不一样?

javascript - 分钟操作后 Momentjs 返回错误的日期

Javascript:使用 Moment js 的自定义日期/时间格式返回 "Invalid date"

javascript - 单击按钮后 JqGrid 不会重新加载

javascript - jQuery - 从具有特定类的元素列表中获取点击项目的索引

Java日历时区转换为GMT问题

c# - 野田时间 - 带区域的一天开始/结束