user2133404
user2133404

Reputation: 1857

moment.unix() not giving correct value for timestamp

I have the following timestamp 1447862653771 which I want to format.

www.epochconverter.com converts it successfully to GMT: Wed, 18 Nov 2015 16:04:13 GMT

I am using moment.js and it is not formatting date correctly.

moment.unix('1447862653771') is giving Tue Dec 10 47850 09:29:31 GMT-0500 (Eastern Standard Time)

$("body").append($("<p>").text(moment.unix('1447862653771')));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/moment.js/1.7.2/moment.min.js"></script>

Upvotes: 1

Views: 2300

Answers (2)

Matt Johnson-Pint
Matt Johnson-Pint

Reputation: 241959

The moment.unix function expects values in terms of whole seconds. Since your value contains milliseconds, you should just pass it in to the moment function, like this:

var m = moment(1447862653771);

While dividing by 1000 as suggested in the other answer may work, it's not ideal, as it relies on the unix function to then multiply by 1000 internally. The decimals are retained, so there is no loss of precision, but it involves two operations that are extraneous, and consumes a few additional bytes of source code.

Upvotes: 1

Halcyon
Halcyon

Reputation: 57721

1447862653771 is in milliseconds, not seconds. Divide by 1000 first. Note that the year is 47850!

moment.unix(1447862653771 / 1000);

or

moment.unix((new Date()).getTime() / 1000);

Also, there is no need to pass the timestamp as a string.

Upvotes: 6

Related Questions