65

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())
  }


}
Feroz Siddiqui
  • 3,840
  • 6
  • 34
  • 69
  • Possible duplicate of [Format date to MM/dd/yyyy in JavaScript](https://stackoverflow.com/questions/11591854/format-date-to-mm-dd-yyyy-in-javascript) – Aravind Jan 10 '18 at 09:04
  • Typescript is a super set of javascript and that solution will work too – Aravind Jan 10 '18 at 09:12
  • u mean i can use same logic of js and used it here. is this a standard way of doing it or typescript will have something inbuilt to handle this – Feroz Siddiqui Jan 10 '18 at 09:13
  • yes you can use the same logic to achieve this. – Aravind Jan 10 '18 at 09:17
  • Problem with Java script it's too open and loose.its restrictive that's why I am using typescript. I don't wanna use javascript. – Feroz Siddiqui Jan 10 '18 at 09:31

4 Answers4

78

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";
Jasper Risseeuw
  • 1,207
  • 11
  • 11
  • Thanks, this worked for me, first it was giving an error, after adding the local to the module it worked! – Mark Nov 05 '20 at 15:20
70

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');
  • thanks mate can u suggest me where can i find tutorial of typescripts? – Feroz Siddiqui Jan 10 '18 at 10:23
  • 1
    Well, all over the internet, but I guess the **[official website](https://www.typescriptlang.org/docs/home.html)** should have the most, and you should also take a look at **[Angular website](https://angular.io/guide/architecture)** because most of your questions will be answered there (including, this one !) –  Jan 10 '18 at 10:25
  • yeah but i couldnt find the any date/Map/Set related topic in the documentation – Feroz Siddiqui Jan 10 '18 at 10:43
  • what is the date/map/set related topic ? What exactly are you looking for ? –  Jan 10 '18 at 10:44
  • i am learning angular 5 i need to understand how should i process the data like Map,Set basicially collections and their sorting order logic inside component file. also need to understand is there is a way to convert Json object to typescript object directly via using third party library like we use GSON in java – Feroz Siddiqui Jan 10 '18 at 10:48
  • Your best shot is to google those questions. That's personally how I learnt it. You seem to come from the Java world, and you want to keep using Maps, Sets and such : opposed to you, I come from the Javascript world and tend to never use this. So when I had questions about that, I usually googled it. But to answer you : 1 - Instead of maps and sets, simply use arrays and objects. It's easier to use and manipulate. To convert JSON objects to TS objects, simply type them with `myObject: MyClass = JsonObject`. You don't need 3rd party libraries for JSON in TS. –  Jan 10 '18 at 10:55
  • can i use this pipe to format datetime in a string format (ex. 2018020509090000) ? – tero17 Jul 17 '18 at 13:22
  • 1
    Try `.transform(yourDate, 'yyyyMMddhhmmss')` or something alike –  Jul 17 '18 at 13:52
  • 1
    If you use any other locale than `en-US`, don't forget to register the locale as described [here](https://angular.io/guide/i18n#i18n-pipes). – Daan Aug 07 '18 at 07:56
  • but the date is not changing to the local language. The result shows like this `23/3/20 1:19 PM`. Although I change the locale. It should show the date according to the locale. – MD. IBRAHIM KHALIL TANIM Mar 23 '20 at 07:18
  • Works great! Remember to import the dependency: import { DatePipe } from '@angular/common'; – Vaughn Jun 13 '20 at 04:51
  • This really shouldn't be the selected answer, the `datePipe` is built on top of the `formatDate` endpoint. Creating an instance of a `datePipe` is unnecessary unless you plan to use it in the HTML. You should just be using `formatDate`. – Dane Brouwer Dec 07 '20 at 12:02
19

Refer to the below link,

https://angular.io/api/common/DatePipe

Usage example from there

@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

General Grievance
  • 4,555
  • 31
  • 31
  • 45
Srinivasan N
  • 733
  • 8
  • 9
16

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'));
Rathma
  • 1,196
  • 2
  • 33
  • 65