Search code examples
momentjsmoment-timezone

momentjs switching between timezone with 12 hours or more difference


I am using moment js to convert the date to UTC like this

var a = moment.utc('20-Oct-2021').tz('Asia/Kolkata');

a.format()

This results 2021-10-20T05:30:00+05:30

Now I am trying to use access this from Newsland that is from this timezone Pacific/Auckland - In system I changed my timezone to this which is +13.

Now the result for

moment().utc(a).format() is

2021-10-21T02:09:12Z

If you notice the date is 21 instead of 20 which is the actual date stored.

Facing problem with all greater than +-12


Solution

  • Changing your timezone doesn't change the timezone of a since its zone is manually set. You need to use local() to get the time in your timezone.

    // Always pass the string format if the string is not an ISO 8601 date
    var a = moment.utc('20-Oct-2021', 'DD-MMM-YYYY').tz('Asia/Kolkata');
    
    console.log(a.format());
    console.log(a.utc().format()); // in UTC
    
    console.log(a.local().format()); // This is in your timezone
    
    a.tz("Pacific/Auckland"); // Change to Auckland
    
    console.log(a.format()); // Auckland time
    console.log(a.local().format()); // In your timezone, as same as above
    <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/moment-timezone/0.5.33/moment-timezone-with-data-10-year-range.min.js"></script>