Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to format date in Component of angular 5

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())   }   } 
like image 322
Feroz Siddiqui Avatar asked Jan 10 '18 09:01

Feroz Siddiqui


People also ask

What is angular date format?

Date Format. Angular datepipe code. Result. M/d/yy, h:mm a.


1 Answers

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"; 
like image 187
Nidhal Ben Tahar Avatar answered Sep 27 '22 20:09

Nidhal Ben Tahar