Seb
Seb

Reputation: 21

How to format a Date field in Angular project

I have a stringVariable coming from the backend service that I have converted into a Date field like below.

date d = new Date(stringVariable );

This worked fine. However the new date output looks like this.

Thu Jun 29 2017 20:00:00 GMT-0400 (Eastern Daylight Time)

I need it to be changes to a different format yyyy-mm-dd and i would need the variable 'd' to remain as a Date not a String.

If I use date pipe transform method or .toLocaleString, it will convert the final output 'd' to a string. That shouldn't happen.

Appreciate help from experts.

Upvotes: 0

Views: 1313

Answers (1)

wentjun
wentjun

Reputation: 42576

You can't change the format of the Date object.

However, in order to solve your problem, you can use date pipe on your template/html. It is natively available in Angular. It will not mutate the value of d, as it merely transform it into your required yyyy-mm-dd format. The value of d on your component.ts will still be in the Date Object format, thus you can continue to use it on other parts of your component. You can check out the accepted formats for the date pipe over here.

<input [ngModel]="d  | date:'yyyy-MM-dd'"/>

You may refer to this short demo.


EDIT: Since you are using PrimeNg's p-calendar component, we can simply make use of the dateFormat property which serves the same purpose as the pipe above.

<p-calendar [(ngModel)]="d" dateFormat="yy-MM-dd"></p-calendar>

Here is a demo. On my demo, I have binded the onSelect event such that it prints the updated d everytime you select a new date.

Upvotes: 2

Related Questions