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!

Zamir
  • 217
  • 2
  • 11
  • 3
    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))`. – RobG Aug 29 '19 at 11:04
  • https://momentjs.com/timezone/docs/#/using-timezones/parsing-in-zone/ -> use `moment.tz(...)`, not `moment(...).tz(...)`. `.tz(...)` is a _conversion_ to a timezone (https://momentjs.com/timezone/docs/#/using-timezones/converting-to-zone/). – Sergiu Paraschiv Aug 29 '19 at 11:08
  • It's just because of `timezone` – Neel Rathod Aug 29 '19 at 11:18
  • @NeelRathod,So how can I get right milliseconds – Zamir Aug 29 '19 at 11:26
  • 1
    You need to pass the timezone, otherwise it will use your default local timezone – Christoph S Aug 29 '19 at 11:27
  • @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. 1567032260000 – Zamir Aug 29 '19 at 11:29

2 Answers2

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();
Darek Gala
  • 157
  • 1
  • 2
  • 7
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.

murli2308
  • 2,976
  • 4
  • 26
  • 47