doc92606
doc92606

Reputation: 701

Time conversion incorrect in momentjs

I am trying to use momentjs to extract and do some time calculations in typescript but...

I am getting incorrect value for time as 11:51 PM

I should be getting 4:51 PM.

const m = moment('2019-03-13T16:51-07:00');
console.log(m.format('LT'));

Upvotes: 1

Views: 203

Answers (1)

PSL
PSL

Reputation: 123739

This is expected because the date-time string input that you are passing to the moment function has timezone offset in it. Moment will convert the input date-time to local date-time based on the timezone offset. If you want to ignore (or rather preserve) the timezone offset and get the exact date-time regardless of the browser timezone, you can use moment.parseZone method.

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.

 const m = moment.parseZone(ISODateTimeString);
 console.log(m.format('LT')); //"03/13/2019 4:51 PM" for en-US locale

// or you can also use

 const m = moment(ISODateTimeString).utcOffset(ISODateTimeString);

Upvotes: 1

Related Questions