I have a web service that is returning a date as the following string:
/Date(1377907200000)/
I use MomentJS to parse this to a moment
object.
moment("/Date(1377907200000)/")
=> Fri Aug 30 2013 20:00:00 GMT-0400
All of that is fine. But when I call unix()
on the object I am given the value 1377907200
. This, however, corresponds to Fri Jan 16 1970 17:45:07 GMT-0500
. I could just multiply the value returned by unix()
but that seems sloppy to me. I suspect that what I am doing by calling unix()
is not exactly what I think it is. Do I need to specify some sort of format when calling unix()
? What am I missing here?
JSFidle showing the conversion to moment and then back.
The moment(). unix() function is used to get the number of seconds since the Unix Epoch.
unix() function to parse unix timestamps (seconds). The moment. unix() function is used to create a moment using Unix Timestamp, seconds since the Unix Epoch (Jan 1 1970 12AM UTC). Parameter: It takes a Number variable which is the number of seconds after the Unix Epoch.
There are several libraries out there that can potentially replace Moment in your app. The creators of Moment recommend looking into Luxon, Day. js, date-fns, js-Joda, or even replacing Moment with native JS.
Just for info, moment. js is not maintained anymore. If you start a new project don't use moment. But if it's an old project, still use it.
The answer provided by meagar is correct, from strictly a JavaScript / Unix time perspective. However, if you just multiply by 1000, you will loose any sub-second precision that might have existed in your data.
Moment.js offers two different methods, as described in the docs. .unix()
returns the value in seconds. It is effectively dividing by 1000 and truncating any decimals. You want to use the .valueOf()
method, which just returns the milliseconds without modification.
In JavaScript land, when you convert a Date
to an integer, you get a number of milliseconds since the unix epoch. Traditional Unix time is the number of seconds since epoch. Multiplying by 1000 is the correct option.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With