17

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.

Robert Kaucher
  • 1,841
  • 3
  • 22
  • 44
  • You don't need to convert to the date object that way, moment can handle `moment(1377907200000)` just fine. Curious why the web service returns the date as such. – mix3d May 01 '15 at 20:45
  • We use a web service that returns it as well-- this is because the target consumer of the API is usually JavaScript, which does "from Epoch in milliseconds" instead of seconds. It's targeted to the most likely consumer. – Greg Pettit Nov 06 '15 at 17:06

3 Answers3

51

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.

Matt Johnson-Pint
  • 230,703
  • 74
  • 448
  • 575
11

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.

user229044
  • 232,980
  • 40
  • 330
  • 338
0

this solution help me to add the format to Epoch date using moment.js.

moment(1377907200000).format("DD MMM YYYY hh:mm A")
Sahil Ralkar
  • 2,331
  • 23
  • 25