Search code examples
javascriptangularjsmomentjsangular-moment

Why moment js gives different milliseconds?


I getting error of different millisecond of same date using moment js.

I am getting data from server ('-2208988800000'). I converted the value in 'DD-MMM-YYYY'. Now I want again same millisecond, why I am getting different milliseconds of same date? Here is my code

http://plnkr.co/edit/1QoWLoFqkNAe2ebZ0V01?p=preview

I have two console x1 and x2. They are different, why?

var x = '-2208988800000'
var d = new Date(moment(new Date(parseInt(x)).toUTCString()).format('DD-MMM-YYYY'));
console.log(d)
var x2 = moment(new Date(d).toUTCString()).format('x');
console.log(x2)
// why x1 and x2 is different
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment.min.js"></script>

How can I get the same value?


Solution

  • When you format the date to DD-MMM-YYYY you're losing hours and minutes, that's part of the reason

    Try updating your code to

    var d = new Date(moment(new Date(parseInt(x)).toUTCString()).format('DD-MMM-YYYY HH:mm:ss'));

    and you will get a timestamp that is closer