MomentJS wrong output
Asked Answered
M

2

6

I am converting Miliseconds to date and time using moment It gives me correct output as expected but while converting same date+time it gives me wrong output.

I have used unix,valueOf moment methods.

const moment = require('moment-timezone');

console.log(moment.tz(1567032260763,'x','America/Chicago').format('MM-DD-YYYY hh:mm:ss A')) //gives me 08-28-2019 05:44:20 PM which is right.

console.log(moment('08-28-2019 05:44:20 PM','MM-DD-YYYY hh:mm:ss A').valueOf());  // gives me 1567032260000 instead of 1567032260763

Please guide where I am wrong!

Mesmerism answered 29/8, 2019 at 10:59 Comment(6)
1567036363000 is the correct value. Chicago is UTC-6, so 08-28-2019 05:52:43 PM is 2019-08-28 23:52:43Z (the hour is 17 + 6 =23), the time value is given by Date.UTC(2019,7,28,23,52,43)).Roots
momentjs.com/timezone/docs/#/using-timezones/parsing-in-zone -> use moment.tz(...), not moment(...).tz(...). .tz(...) is a conversion to a timezone (momentjs.com/timezone/docs/#/using-timezones/converting-to-zone).Capitol
It's just because of timezoneLeadsman
@NeelRathod,So how can I get right millisecondsMesmerism
You need to pass the timezone, otherwise it will use your default local timezoneThroat
@ChristophS I passed the timezone as well, moment.tz(''08-28-2019 05:44:20 PM','MM-DD-YYYY hh:mm:ss A'',''America/Chicago'').valueOf(). But the output is same ie. 1567032260000Mesmerism
N
0

You need to add timezone in this line:

moment('08-28-2019 05:44:20 PM','MM-DD-YYYY hh:mm:ss A').tz('America/Chicago').valueOf();
Norvin answered 29/8, 2019 at 11:49 Comment(1)
Darek,I had already tested before your answer it unfortunately it is not working!Mesmerism
L
0

function callMoment() {
console.log(moment.tz(1567032260763,'x','America/Chicago').format('MM-DD-YYYY hh:mm:ss A'))

console.log(moment.tz('08-28-2019 05:44:20.763 PM','MM-DD-YYYY hh:mm:ss.S A','America/Chicago').valueOf());
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment-with-locales.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment-timezone/0.5.26/moment-timezone-with-data.min.js"></script>
<button onclick="callMoment()">Call Me</button>

You are missing milliseconds while converting it back.

console.log(moment.tz(1567032260763,'x','America/Chicago').format('MM-DD-YYYY hh:mm:ss A'))

console.log(moment.tz('08-28-2019 05:44:20.763 PM','MM-DD-YYYY hh:mm:ss.S A','America/Chicago').valueOf());

Now the output is correct.

Lara answered 29/8, 2019 at 12:44 Comment(1)
Oh! I am deleting my last comment,The output is not correct.Mesmerism

© 2022 - 2024 — McMap. All rights reserved.