Javascript 使用 MomentJs 显示日期时间,无需时区转换
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28198626/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Display datetime with MomentJs without timezone conversion
提问by Sgraffite
Sometimes I end up with a datetime on the front end of a web site that has already been adjusted to a specific time zone, and I wish to display it exactly as is regardless of the user's timezone.
有时,我最终会在网站的前端显示一个日期时间,该日期时间已经调整到特定时区,我希望无论用户的时区如何,都完全按原样显示它。
For example let's say I have this date:
例如,假设我有这个日期:
2015-01-22T16:11:36.36-07:00
2015-01-22T16:11:36.36-07:00
The -07:00 means it is in Mountain Time, and MomentJs knows this and will automatically adjust for users in other timezones. For example say I display the datetime with this code:
-07:00 表示现在是山地时间,MomentJs 知道这一点,并会自动为其他时区的用户进行调整。例如说我用这个代码显示日期时间:
moment('2015-01-22T16:11:36.36-07:00').format('l LT')
A user in Central time (-06:00) will see the time as 5:11PM instead of 4:11PM. How can I tell MomentJs to not adjust for the user's timezone and display the datetime as is?
中部时间 (-06:00) 的用户将看到时间为下午 5:11 而不是下午 4:11。我如何告诉 MomentJs 不要调整用户的时区并按原样显示日期时间?
回答by musicfuel
Use the utc()method of moment to remove the timezone and display everything in universal time.
使用utc()moment的方法去除时区并以世界时显示所有内容。
moment.utc('2015-01-22T16:11:36.36-07:00').format('l LT')
That will display the time as it is in UTC without any timezone offset. If you want to display the time as it was recorded in the user/server timezone you can parse the zone information when you construct a moment instance and have it use the timezone recorded in the parsed string.
这将显示 UTC 中的时间,没有任何时区偏移。如果您想显示在用户/服务器时区中记录的时间,您可以在构建时刻实例时解析时区信息,并让它使用在解析字符串中记录的时区。
moment.parseZone('2015-01-22T16:11:36.36-07:00').format('l LT');
With either of these approaches you should consider labeling the time in some way to reflect the timezone the time corresponds to. Failing to do this could lead to a lot of confusion for the end users.
使用这些方法中的任何一种,您都应该考虑以某种方式标记时间以反映时间对应的时区。如果不这样做,可能会给最终用户带来很多困惑。
回答by merqlove
回答by Sgraffite
I created an extension to display the datetime without trying to adjust to the user's timezone:
我创建了一个扩展来显示日期时间而不尝试调整到用户的时区:
(function (moment) {
moment.fn.nozone = function () {
var m1 = moment(this);
var offsetInMinutes = m1.utcOffset();
return m1.utc().add(offsetInMinutes, 'm');
};
}(moment));
This way it is easily reusable, even in javascript templates.
这样,即使在 javascript 模板中,它也很容易重用。

