10

I have a timestamp 1378028575 that gives me Sun, 01 Sep 2013 09:42:55 GMT here. But when I try to format it with Angular date, it returns it as Jan 17, 1970 2:47:08 AM, using this format: {{'1378028575' | date:'medium'}}. The result from the site is correct but in Angular is wrong. Why does it happen, or what am I doing wrong?

Sergei Basharov
  • 51,276
  • 73
  • 200
  • 335

2 Answers2

19

Its cause you use seconds not milliseconds.

new Date(1378028575)
Fri Jan 16 1970 23:47:08 GMT+0100 (CET)

new Date(1378028575000)
Sun Sep 01 2013 11:42:55 GMT+0200 (CEST)

from the angular docs:

Date to format either as Date object, milliseconds (string or number) or various ISO 8601 datetime string formats (e.g. yyyy-MM-ddTHH:mm:ss.SSSZ and its shorter versions like yyyy-MM-ddTHH:mmZ, yyyy-MM-dd or yyyyMMddTHHmmssZ). If no timezone is specified in the string input, the time is considered to be in the local timezone.

Andreas Köberle
  • 106,652
  • 57
  • 273
  • 297
  • 1
    Then seems like the answer given here http://stackoverflow.com/questions/17925020/angularjs-convert-tag-value-unix-time-to-human-readable-time is not correct? They talk about unix time there and seems like the OP will have the same issues. – Sergei Basharov Sep 09 '13 at 10:47
  • Thanks, this worked for me. I'm using Stripe, and it returns all times as seconds rather than milliseconds. Multiplying every date by 1000 did the trick! – htxryan Nov 13 '13 at 13:34
13

The other answer isnt quite complete. Since your timestamp is in seconds, not miliseconds, in Angular.js you can do this:

{{1378028575 * 1000 | date:'medium'}}

Knowing seconds * 1000 = miliseconds is one thing. Knowing you can put math in the date expression is another :)

Jordy Kirkman
  • 180
  • 1
  • 7
  • This is likely the better answer for most people goggling this. I was trying to decided where to address this after reading the initial answer. Ideally, I would have liked to address this in my service but it returns a promise. This left me with the controller, but if another controller ever uses this service I would have to repeat the code or make a helper functions. Then I read your answer. Ideally the service would be the place to handle this but I'm not sure it is possible with a complete rewrite. – Michael Hobbs Jun 24 '15 at 22:53