简体   繁体   中英

Moment-Timezone is not changing the date/time for the specified region

I am using moment and moment-timezone to output the airdate/time of a given TV Show (for any timezone)

The host timezone is America/Chicago

In the example below, the dateTime passed in is a TV show that airs in 3 hours. Which is Sunday at 9:00PM in America/Chicago, and Monday at 4:00 AM in Europe/Zagreb:

  determineAirTime(dateTime) {
    console.log(dateTime); // July 16th 2017 9:00PM

    dateTime = 
 momentTimezone.tz(dateTime, "MMM Do YYYY hA", momentTimezone.tz.guess());

    dateTime = dateTime.format(); // this creates: 2017-07-16T21:00:00-05:00

   // moment
   moment(dateTime).calendar(); // Today at 9:00 PM
  }

For my timezone (America/Chicago), Today at 9:00 PM is correct. However, it always outputs Sunday 9:00 pm for any timezone, which is incorrect.

Here is an example of the same data we used in our example, but with a different timezone:

在此处输入图片说明

The correct output for the above would be Monday at 4:00 AM .

How can I fix my program so that it prints out the correct air/date times for the timezone?

If you start with a date string for UTC-06:00 on 23 July at 21:00, then you'll have a date like:

var s = '2017-07-23T21:00:00-0600';

To output that in an equivalent timezone for say Zagreb which is UTC+01:00, use:

 var s = '2017-07-23T21:00:00-0600'; var d = moment(s); console.log('America/Chicago: ' + d.tz('America/Chicago').format('dddd D MMMM, YYYY hh:mm a')); console.log('Europe/Zagreb: ' + d.tz('Europe/Zagreb').format('dddd D MMMM, YYYY hh:mm a')); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/moment-timezone/0.5.13/moment-timezone-with-data.min.js"></script> 

Observe:

var dateTime = 'July 16th 2017 9:00PM';  // as you said in your question

// create a moment object in the original time zone
var m = moment.tz(dateTime, 'MMM Do YYYY h:mmA', 'America/Chicago');

// switch to the target time zone and format back to a string
var s = m.tz('Europe/Zagreb').format('MMM Do YYYY h:mmA');  // 'Jul 17th 2017 4:00AM'

Also, in your code you used moment.tz.guess() . That is unnecessary. If you meant to use the local time zone, then just call the local function. In other words, change the last line of what I wrote above to:

var s = m.local().format('MMM Do YYYY h:mmA');

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