12

http://plnkr.co/edit/5zxXEEz30t51yGhgYWVF?p=preview

I'm using Moment.js and Angular-moment in my app.

For some reason it's converting all my epoch timestamps to the same date from 1970.

enter image description here

<td class="timespan">{{tag.added_epoch | amDateFormat:'dddd, MMMM Do YYYY'}}</td>

This is what the tag.added_epoch value is added_epoch: 1432252800

However when I convert it online, I get the correct date:

enter image description here

Any idea why my filter is turning 1432252800 into Saturday, January 17th 1970?

Leon Gaban
  • 36,509
  • 115
  • 332
  • 529
  • 1
    Have you tried `moment.unix()` in angular-moment it would be `` – Arminmsg Jan 29 '16 at 20:28
  • 1
    I get this error `Unknown provider: amFromUnixFilterProvider <- amFromUnixFilter` looks like I need to use a different version of the lib :( but are my numbers correct? – Leon Gaban Jan 29 '16 at 20:33
  • 1
    I've took a quick look at moment.js and I get 1970 if I just use `moment(1432252800)` I get the 1970 date with the `unix` method I get the 2015 date, so your numbers seem to be correct. From the angular-moment docs: Note: To use amFromUnix, install angular-moment version 1.0.0-beta.3 – Arminmsg Jan 29 '16 at 20:36
  • @Arminmsg how? They don't have that build up :( https://github.com/urish/angular-moment/releases oh nvm found it on the CDN https://cdnjs.cloudflare.com/ajax/libs/angular-moment/1.0.0-beta.3/angular-moment.min.js – Leon Gaban Jan 29 '16 at 20:42
  • @Arminmsg ok I got it looking better: http://plnkr.co/edit/5zxXEEz30t51yGhgYWVF?p=preview still need to format it however, but at least it looks like I'm getting the correct year in there finally. – Leon Gaban Jan 29 '16 at 20:47
  • 1
    The latest build is the 1.0.0-beta3, take a look at the label – Arminmsg Jan 29 '16 at 20:47

2 Answers2

24

I'm just quickly summarizing the problem and solution.

Moment.js offers two different ways to create a date from a unix timestamp moment(1432252800) and moment.unix(1432252800).

Both start at the same time (Jan 1 1970 12AM UTC) but moment() uses the number as milliseconds, which are around 17 days and moment.unix() uses seconds.

angular-moment supports the amFromUnix filter, see source

You can use it the following way

<time am-time-ago="myDate|amFromUnix">
{{myDate|amFromUnix|amCalendar}}
Arminmsg
  • 601
  • 5
  • 15
5

Try to write own filter, like this:

 newapp.filter("fromTimestamp", function(){
   return function(timestamp, format){
     return moment.unix(timestamp).format(format)
   }
 })

And use them

<p class="date">{{date | fromTimestamp:'dddd, MMMM Do YYYY'}}</p>

Plunker demo

Enver Dzhaparoff
  • 4,341
  • 3
  • 19
  • 21