1

I have a date being displayed in my Angular 2 app that is printing in an undesired format, like this: 2012-04-02T00:00:00.000Z

What I'd like to do is use Angular's date pipe to transform this data so it prints in a more human-friendly format. Is there a way I can use the date pipe on an input where I'm using two-way binding? In other words, can I use the date pipe on code that looks like this?

<input class="app-input" [(ngModel)]="staff.profile.hireDate" placeholder="None"/>

I've tried various attempts, but so far have been unable to do make it work. I'm therefore wondering if it's possible.

And, if not, what would be an alternative way I could handle this via plain JS? I'm open to whatever possibility is effective and simplest to implement.

Rey
  • 1,393
  • 1
  • 15
  • 24

1 Answers1

1

You can do this in your component.

import { DatePipe } from '@angular/common';

then either add it to the providers array in component or in your ngModule.

In your component you inject this in your constructor:

constructor(private myDatePipe: DatePipe) {}

and modify your variable property:

this.staff.profile.hireDate = 
    this.myDatePipe.transform(new Date(this.staff.profile.hireDate));

if you want to specify the output, here for example using the 'short' option:

this.staff.profile.hireDate = 
    this.myDatePipe.transform(new Date(this.staff.profile.hireDate), 'short');
AT82
  • 71,416
  • 24
  • 140
  • 167