Format date with angular2 moment

15.5k views Asked by At

I'm getting following error, when using amTimeAgo pipe from angular2-moment.

Deprecation warning: value provided is not in a recognized RFC2822 or ISO format.
moment construction falls back to js Date(), which is not reliable across all browsers and versions.
Non RFC2822/ISO date formats are discouraged and will be removed in an upcoming major release.
Please refer to http://momentjs.com/guides/#/warnings/js-date/ for more info.
Arguments: [0] _isAMomentObject: true, _isUTC: false, _useUTC: false, _l: undefined, _i: 21-03-2017, _f: undefined, _strict: undefined, _locale: [object Object]

Also pipe is printing Invalid date.

I'm using it like this: <span class="date-created"> {{ job.createdAt | amTimeAgo }} </span>

And value of job.createdAt is string in format: 22-03-2017.

I understand that something is wrong with format, but don't know how to pass that custom format ('DD-MM-YYYY') to pipe, so that moment package and this angular library can recognize it.

Any ideas?

3

There are 3 answers

0
Batajus On BEST ANSWER

What about creating a new moment object to pass it into the pipe, like:

let newMomentObj = moment(job.createdAt, 'DD-MM-YYYY'); 

and in your html file:

<span class="date-created"> {{ newMomentObj | amTimeAgo }} </span>
1
Lambo14 On

I guess, the string is not being correctly converted to date.. you can try below two options:

{{job.createdAt |  date:'MM/dd/yyyy' | amTimeAgo }}

or convert the string to date in your typescript file:

let newDate = new Date(job.createdAt);
0
VincenzoC On

angular2-moment introduced from version 1.4.0 amParse pipe that:

Parses a custom-formatted date into a moment object that can be used with the other pipes

In your case, you can do something like the following:

<span class="date-created"> {{ job.createdAt | amParse:'DD-MM-YYYY' | amTimeAgo }} </span>

this way you can parse your date string directly in your view.