简体   繁体   English

使用Moment时区格式化指定时区中的日期

[英]Formatting date in specified timezone using Moment Timezone

If you change time zone to (UTC-07:00) Mountain Time and run the code below you can see the problem that I'm talking about. 如果您将时区更改为(UTC-07:00)山区时间并运行下面的代码,则可以看到我正在谈论的问题。

 var a = moment('2009-11-01T06:00:00Z').tz('US/Mountain').format(); var b = moment('2009-11-01T06:00:00Z').tz('US/Mountain').format('YYYY-MM-DD HH:mm'); var c = moment('2009-10-31T23:00:00-07:00').format('YYYY-MM-DD HH:mm'); document.getElementById("a").innerHTML = "#1: " + a; document.getElementById("b").innerHTML = "#2: " + b; document.getElementById("c").innerHTML = "#3: " + c; 
 <script src="http://momentjs.com/downloads/moment.min.js"></script> <script src="http://momentjs.com/downloads/moment-timezone-with-data-2010-2020.min.js"></script> <div id="a"></div> <div id="b"></div> <div id="c"></div> 

The date offset produced by running the code (#1) above is correct. 通过运行上面的代码(#1)产生的日期偏移是正确的。 However, shouldn't formatting it change the value to "2009-11-01 00:00" (#3) instead of "2009-10-31 23:00" (#2)? 但是,是否不应该将其格式化将其值更改为“ 2009-11-31 03:00”(#3)而不是“ 2009-10-31 23:00”(#2)?

It seems like the formatter just strips the offset instead of taking it into account when producing the formatted date. 似乎格式化程序只是剥离偏移量,而不是在生成格式化日期时将其考虑在内。 Is this a bug or am I doing something wrong here? 这是一个错误还是我在这里做错了什么?

You are using moment-timezone-with-data-2010-2020.min.js with year 2009. You should change Moment Timezone to moment-timezone-with-data.min.js . 您正在使用2009年的moment-timezone-with-data-2010-2020.min.js 。您应该将Moment Timezone更改为moment-timezone-with-data.min.js See working code snippet: 查看工作代码段:

 var a = moment('2009-11-01T06:00:00Z').tz('US/Mountain').format(); var b = moment('2009-11-01T06:00:00Z').tz('US/Mountain').format('YYYY-MM-DD HH:mm'); var c = moment('2009-10-31T23:00:00-07:00').format('YYYY-MM-DD HH:mm'); document.getElementById("a").innerHTML = "#1: " + a; document.getElementById("b").innerHTML = "#2: " + b; document.getElementById("c").innerHTML = "#3: " + c; 
 <script src="http://momentjs.com/downloads/moment.min.js"></script> <script src="http://momentjs.com/downloads/moment-timezone-with-data.min.js"></script> <div id="a"></div> <div id="b"></div> <div id="c"></div> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM