I am new to angular and looking to format date in component ngOnInit method. I have seen some example where pipe operator are used to format the data but i dont know how to format date in component file.
below is code
export class DashboardComponent implements OnInit {
formatdate = 'dd/MM/yyyy';
constructor(private auth: AuthService) { }
ngOnInit() {
console.log(new Date().toISOString())
}
}
This question is related to
angular
angular-cli
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
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";
Source: Stackoverflow.com