Moment.js amDateFormat always returning date from 1970
Asked Answered
M

2

14

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?

Martymartyn answered 29/1, 2016 at 20:21 Comment(6)
Have you tried moment.unix() in angular-moment it would be <span am-time-ago="message.unixTime | amFromUnix">Bond
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?Martymartyn
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.3Bond
@Bond how? They don't have that build up :( github.com/urish/angular-moment/releases oh nvm found it on the CDN cdnjs.cloudflare.com/ajax/libs/angular-moment/1.0.0-beta.3/…Martymartyn
@Bond ok I got it looking better: 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.Martymartyn
The latest build is the 1.0.0-beta3, take a look at the labelBond
B
26

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}}
Bond answered 29/1, 2016 at 20:59 Comment(0)
E
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

Electricity answered 29/1, 2016 at 20:56 Comment(2)
Thanks! +1 that is super clean :) Arminmsg however did answer my exact question, but your solution may actually be used to replace our code.Martymartyn
@LeonGaban Thanks for +1)Electricity

© 2022 - 2024 — McMap. All rights reserved.