Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to retain timezone when formatting a date in moment.js?

I have a date like 2015-10-24T17:12-05:00 and I'm using moment.js to format it like this:

moment('2015-10-24T17:12-05:00').format('h:mm A');

Instead of showing the time in the timezone specified in the string, moment.js seems to be converting it to the timezone of my computer. How can I preserve the timezone when I am formatting?

like image 654
JackH Avatar asked Oct 30 '22 17:10

JackH


1 Answers

var estTime = '2019-09-01T14:30:00-04:00';
var istTime = "2019-10-01T23:20:00+05:30";
console.log(estTime , "  ", moment(estTime).format("hh:mm") ," ", moment.parseZone(estTime).format("hh:mm"));
console.log(istTime, "  ", moment(istTime).format("hh:mm"), " ", moment.parseZone(istTime).format("hh:mm"));

Moment's string parsing functions like moment(string) and moment.utc(string) accept offset information if provided, but convert the resulting Moment object to local or UTC time. In contrast, moment.parseZone() parses the string but keeps the resulting Moment object in a fixed-offset timezone with the provided offset in the string.

parseZone

Output:

2019-09-01T14:30:00-04:00 02:30 02:30

2019-10-01T23:20:00+05:30 01:50 11:20

like image 108
unni_ramachandran Avatar answered Nov 14 '22 13:11

unni_ramachandran