简体   繁体   中英

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.

 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. However, shouldn't formatting it change the value to "2009-11-01 00:00" (#3) instead of "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 . 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> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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