使用 momentjs 在特定时区设置特定时间 [英] Set specific time in specific timezone using momentjs

查看:191
本文介绍了使用 momentjs 在特定时区设置特定时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在制作一个网络应用程序,我的用户需要选择特定时区中的特定时间.例如,选择 2013 年 11 月 8 日中午在纽约市.不幸的是,我无法在 momentjs 对象中正确设置日期.

I am making a web-app and my users need to select a specific time in a specific time zone. For example, selecting 8th November 2013 at noon in New York City. Unfortunately, I cannot properly set the date in the momentjs object.

这是一个重现我的问题的 jsfiddle.我做错了什么?

Here is a jsfiddle that reproduces my problem. What am I doing wrong?

var data = {date: 8, hour: 12, minute: 0, month: 10, year: 2013}
var ret = moment({}).tz("America/New_York");
_.each(data, function(val,key){
   ret.set(key, val);
});
$("h1").text("the date should be the 8 th but it is the "+ ret.utc().get("date")) // 7

非常感谢,

迪迪尔

推荐答案

您的脚本有点复杂,但它看起来确实工作.至少,我在 Google Chrome 中没有收到错误消息.其他浏览器可能会有所不同.

Your script is a bit convoluted, but it does seem to work in the fiddle. At least, I don't get an error in Google Chrome. Other browsers may vary.

但是,它不会总是产生正确的结果.当您初始化它时,您将在纽约设置一个时刻为现在".但是,您一次替换一个属性的值.这并没有考虑到由于夏令时波动,现在"可能与您提供的日期没有相同的偏移量.

However, it's not going to always produce the correct results. When you initialize it, you are setting a moment as of "now" in New York. But then you replace the values one property at a time. This doesn't take into account that "now" might not have the same offset as the date you are feeding it due to daylight saving time fluctuations.

Moment-timezone 目前没有从特定区域的时间创建时刻的功能.这已在 issue #11 中请求,并且有一个拉取请求已合并在 #25 中,但尚未发布.如果你想使用源码的开发版,现在就可以试试,比如:

Moment-timezone doesn't currently have functionality to create a moment from a time in a particular zone. This has been requested in issue #11, and there is a pull-request that has been merged in #25, but has not yet been released. If you want to work with the development version from the sources, you can try it out now, such as follows:

var m = moment.tz("2013-10-08T12:00:00","America/New_York");

这篇关于使用 momentjs 在特定时区设置特定时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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