convert time stamp to Date inside angular expression like {{new Date(timestamp)}}

All we need is an easy explanation of the problem, so here it is.

Today I found that’s it’s not working to convert for a date inside angular expression.

So I just making something like

<th>{{new Date(elem.timestamp}}</th>

But it fails with internal angular error.

So why it’s not possible to cast to Date inside angular expression?

How to solve :

I know you bored from this bug, So we are here to help you! Take a deep breath and look at the explanation of your problem. We have many solutions to this problem, But we recommend you to use the first method because it is tested & true method that will 100% work for you.

Method 1

Because angular expressions do not accept arbitrary Javascript code, including creating new objects. What you are looking for is called angular filters, they were specifically designed for this case.

So instead of

{{new Date(elem.timestamp)}}

you should write

{{elem.timestamp | date: 'yyyy-MM-dd'}}

More info on the date filter can be found here. More on filters, in general, can be found here.

Method 2

If you are dealing with Firebase Timestamp object (https://firebase.google.com/docs/reference/android/com/google/firebase/Timestamp), you can use:

{{elem.timestamp.seconds*1000 | date}}

Method 3

Just an extention of what @package mentioned we can also go to hour-second as well from millisecond, the format can be any pattern as well

< th >{{elem.timestamp | date: 'yyyy/MM/dd h:mm:ss a'}}< /th >

Method 4

Dealing with Firebase timestamp I use :

{{ element.seconds * 1000| date:'short' }}

Method 5

It is probably best to use a library like moment for this. Also the functionality you are looking for is meant to be implemented via “filters

Also see angular-moment

Method 6

When the timestamp is in milliseconds:
Only Date:

{{elem.timestamp | date: 'yyyy-MM-dd'}}

Date & Time:

{{elem.timestamp | date: 'yyyy/MM/dd hh:mm:ss a'}}

Date & Time(24-hr format):

{{elem.timestamp | date: 'yyyy/MM/dd HH:mm:ss'}}

When your timestamp is in seconds, then just multiply with 1000:

{{elem.timestamp*1000 | date: 'yyyy/MM/dd HH:mm:ss'}}

Method 7

It’s working to convert for a date inside an Angular expression.

So I just making something like:

{{elem.timestamp | date: 'yyyy-MM-dd'}}

Note: Use and implement method 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply