0

I am trying to format a date input to display only yyyy/MM/dd. I am getting the date from an API GET call which returns the date as yyyy-MM-ddThh:mm:ss.ms+Z in the response body as Json

{... date: "2020-06-30T08:04:11.9775152+02:00" ...} //ommited for brevity

My input is two-way bounded

<input type="date" [(ngModel)]="date">

But the input's value remains yyyy/MM/dd. Any ideas on how I can format the date correctly on either HTML/TS side?

R. Richards
  • 24,603
  • 10
  • 64
  • 64
Dylan Smyth
  • 162
  • 11
  • The `value` of an `input type="date"` is always in ISO 8601 format. You cannot format a date shown in an `input type="date"`. – Heretic Monkey Jun 30 '20 at 12:09

2 Answers2

1

First thing to know, you can't use pipe on template statement which mean that you can't do [(ngModel)]="date | date 'yyyy/MM/dd'". So, in your case, you need to split your two templates.

Here a working example

<input [ngModel]="date | date:'yyyy/MM/dd'" (ngModelChange)="date = $event"/>

Your [ngModel] template will get the value of date with the pipe you want, here yyyy/MM/dd, and your (ngModelChange) template will change the value of date when you update it.

Alexis
  • 1,685
  • 1
  • 12
  • 30
  • Don't use `new Date(string)` unless the string is a date in ISO 8601 format (i.e. yyyy-mm-dd (with dashes)). With any other format, the success of the parse will depend on browser/OS/regional settings. See [Why does Date.parse give incorrect results?](https://stackoverflow.com/q/2587345/215552) – Heretic Monkey Jun 30 '20 at 12:14
  • Oh thank, didn't knew it I have edited the post, and also I understand some problems on my projects :$ – Alexis Jun 30 '20 at 12:17
1

write the following code in .ts

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

constructor(private datePipe: DatePipe) { 
    }

  ngOnInit() {
//write format you want.
let dateFormat = 'yyyy/MM/dd';
let myDate = new Date('2020-06-30T08:04:11.9775152+02:00');
    this.date = datePipe.transform(myDate,dateFormat);

}
surendra kumar
  • 1,686
  • 11
  • 15