how to format date in Component of angular 5
Another option can be using built in angular formatDate function. I am assuming that you are using reactive forms. Here todoDate
is a date input field in template.
import {formatDate} from '@angular/common';
this.todoForm.controls.todoDate.setValue(formatDate(this.todo.targetDate, 'yyyy-MM-dd', 'en-US'));
Refer to the below link,
https://angular.io/api/common/DatePipe
**Code Sample**
@Component({
selector: 'date-pipe',
template: `<div>
<p>Today is {{today | date}}</p>
<p>Or if you prefer, {{today | date:'fullDate'}}</p>
<p>The time is {{today | date:'h:mm a z'}}</p>
</div>`
})
// Get the current date and time as a date-time value.
export class DatePipeComponent {
today: number = Date.now();
}
{{today | date:'MM/dd/yyyy'}} output: 17/09/2019
or
{{today | date:'shortDate'}} output: 17/9/19
You can find more information about the date pipe here, such as formats.
If you want to use it in your component, you can simply do
pipe = new DatePipe('en-US'); // Use your own locale
Now, you can simply use its transform method, which will be
const now = Date.now();
const myFormattedDate = this.pipe.transform(now, 'short');
There is equally formatDate
const format = 'dd/MM/yyyy';
const myDate = '2019-06-29';
const locale = 'en-US';
const formattedDate = formatDate(myDate, format, locale);
According to the API it takes as param either a date string, a Date object, or a timestamp.
Gotcha: Out of the box, only en-US
is supported.
If you need to add another locale, you need to add it and register it in you app.module, for example for Spanish:
import { registerLocaleData } from '@angular/common';
import localeES from "@angular/common/locales/es";
registerLocaleData(localeES, "es");
Don't forget to add corresponding import:
import { formatDate } from "@angular/common";