MomentJS convert from UTC to desired timezone, not just local
Asked Answered
U

6

26

I am using momentjs but having an issue trying to convert a UTC time to a specific timezone (not necessarily local to the current user) that is specified by name 'America/New_York'. This SO question is similar but didn't really help.

My thought process is to create a utc moment obj with the received date from the server and then format that UTC time to the specific timezone for display purposes. A small snippet of how I'm currently approaching this:

var cutoffString = '20170421 16:30:00'; // in utc
var utcCutoff = moment.tz(cutoffString, 'YYYYMMDD HH:mm:ss', '+00:00');
var displayCutoff = 
        moment.tz(utcCutoff.format('YYYYMMDD HH:mm:ss'), 'YYYYMMDD HH:mm:ss', 'America/New_York');

console.log('utcCutoff:', utcCutoff.format('YYYYMMDD hh:mm:ssa Z')); // => utcCutoff: 20170421 04:30:00pm +00:00
console.log('displayCutoff:', displayCutoff.format('YYYYMMDD hh:mm:ssa Z')); // => displayCutoff: 20170421 04:30:00pm +00:00

My assumption here is that displayCutoff would be the utcCutoff time displayed in 'America/New_York' time. But it currently is displays the same time as the utcCutoff object. I also should mention that using .utc() instead of .tz and trying to manipulate the timezone after applying .local() did not work either.

Any help/guidance would be appreciated.

Upi answered 20/4, 2017 at 17:9 Comment(1)
Here an example on how convert moment between timezone that could help you.Deplume
D
33

You can use moment.utc since your input is an UTC string. You can use tz to convert your moment object to a given timezone.

Please note that the tz function converts moment object to a given zone, while you are using moment.tz parsing function that builds a new moment object with the given zone. When you do:

var displayCutoff = 
    moment.tz(utcCutoff.format('YYYYMMDD HH:mm:ss'), 'YYYYMMDD HH:mm:ss', 'America/New_York');

you are not converting utcCutoff to 'America/New_York' but you are building a new moment object for 20170421 16:30:00 in New York.

Here an updated version of your code:

var cutoffString = '20170421 16:30:00'; // in utc
var utcCutoff = moment.utc(cutoffString, 'YYYYMMDD HH:mm:ss');
var displayCutoff = utcCutoff.clone().tz('America/New_York');

console.log('utcCutoff:', utcCutoff.format('YYYYMMDD hh:mm:ssa Z')); // => utcCutoff: 20170421 04:30:00pm +00:00
console.log('displayCutoff:', displayCutoff.format('YYYYMMDD hh:mm:ssa Z')); // => displayCutoff: 20170421 12:30:00pm -04:00
<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.11/moment-timezone-with-data-2010-2020.min.js"></script>
Deplume answered 20/4, 2017 at 18:28 Comment(2)
This is exactly what I needed. One thing I noted is that the cdn I was pointing to for moment-timezone 0.5.13 did not have the data included and therefore was still displaying the time in UTC with your solution. When I added the latest packed data, things worked as your sample did.Upi
This is basically what is SO unclear from the momentJs documentation. Many thanks Vicenzo.Darius
F
7

With momentjs-timezone you can convert from any timezone to any other timezone.

You need to specify the start time zone and before formatting the target timezone.

Here is an example which converts a date time from UTC to three other timezones:

const moment = require('moment-timezone')

const start = moment.tz("2021-12-08T10:00:00", "UTC") // original timezone

console.log(start.tz("America/Los_Angeles").format())
console.log(start.tz("Asia/Calcutta").format())
console.log(start.tz("Canada/Eastern").format())

This will print out:

2021-12-08T02:00:00-08:00
2021-12-08T15:30:00+05:30
2021-12-08T05:00:00-05:00

Instead of UTC as start timezone you can use any other timezone too, like "Asia/Seoul" and obviously get different results with the same script:

const moment = require('moment-timezone')

const start = moment.tz("2021-12-08T10:00:00", "Asia/Seoul")

console.log(start.tz("America/Los_Angeles").format())
console.log(start.tz("Asia/Calcutta").format())
console.log(start.tz("Canada/Eastern").format())

This prints out:

2021-12-07T17:00:00-08:00
2021-12-08T06:30:00+05:30
2021-12-07T20:00:00-05:00

All momentjs timezones are listed here:

https://gist.github.com/diogocapela/12c6617fc87607d11fd62d2a4f42b02a

Feaster answered 8/12, 2021 at 10:51 Comment(0)
F
6

Moment timezone plugin is exactly what you need : http://momentjs.com/timezone/

var dec = moment("2014-12-01T12:00:00Z");
dec.tz('America/New_York').format('ha z');  // 5am PDT
Fresno answered 20/4, 2017 at 19:0 Comment(1)
If it's 12:00 in UTC time, surely it cannot be 05:00 in New York time. PDT is the timezone on the west coast.Filtrate
G
0

Seems like moment .parseZone 2.3.0+ is what you need:

const inputDate = '2023-05-28T00:00:00+11:00';
const parsedDate = moment(inputDate);
console.log(parsedDate.format('DD/MM/YYYY')); // 27/05/2023
parsedDate.parseZone();
console.log(parsedDate.format('DD/MM/YYYY')); // 28/05/2023
Gleason answered 26/1 at 8:42 Comment(0)
D
0

its easier if you have the zone offset value.like I used for IST (+5:30)

const getIST = (utc) => {
 return moment(utc).utc().add(5.5, 'h');
}

let utcDate= "2024-07-03T12:30:00";
console.log(getIST(utcDate)); // "2024-07-03T18:00:00"
Drucilladrucy answered 3/7 at 8:27 Comment(0)
D
-4

There is no need to use MomentJs to convert your timezone to specific timezone. Just follow my given below code, it will work for you :

$(document).ready(function() {
   //EST
setInterval( function() {
var estTime = new Date();
 var currentDateTimeCentralTimeZone = new Date(estTime.toLocaleString('en-US', { timeZone: 'America/Chicago' }));
var seconds = currentDateTimeCentralTimeZone.getSeconds();
var minutes = currentDateTimeCentralTimeZone.getMinutes();
var hours =  currentDateTimeCentralTimeZone.getHours();//new Date().getHours();
 var am_pm = currentDateTimeCentralTimeZone.getHours() >= 12 ? "PM" : "AM";

if (hours < 10){
     hours = "0" + hours;
}

if (minutes < 10){
     minutes = "0" + minutes;
}
if (seconds < 10){
     seconds = "0" + seconds;
}
    var mid='PM';
    if(hours==0){ //At 00 hours we need to show 12 am
    hours=12;
    }
    else if(hours>12)
    {
    hours=hours%12;
    mid='AM';
    }
    var x3 = hours+':'+minutes+':'+seconds +' '+am_pm
// Add a leading zero to seconds value
$("#sec").html(x3);
},1000);


});
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

</head>
<body>
<p class="date_time"><strong id="sec"></strong>  </p>


</body>
</html>
Dismember answered 16/10, 2018 at 10:23 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.