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()) } }
Date Format. Angular datepipe code. Result. M/d/yy, h:mm a.
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";
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With