Open In App

Angular 10 formatDate() Method

Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we are going to see what is formatDate in Angular 10 and how to use it. formatDate is used to format a date according to locale rules.

Syntax:

formatDate(value, locale, format, timezone)

Parameters:

  • value: The number to format.
  • locale: A locale code for the locale format.
  • format: The date-time components to include.
  • timezone: The time zone of the place.

Return Value:

  • string: the formatted date string.

NgModule: Module used by formatDate is:

  • CommonModule

Approach: 

  • Create the Angular app to be used.
  • In app.module.ts import LOCALE_ID because we need locale to be imported for using get formatDate.
import { LOCALE_ID, NgModule } from '@angular/core';
  • In app.component.ts import formatDate and LOCALE_ID
  • inject LOCALE_ID as a public variable.
  • In app.component.html show the local variable using string interpolation
  • Serve the angular app using ng serve to see the output.

Example 1:

app.component.ts




import {
  formatDate
 }
  from '@angular/common';
  
import {Component,
  Inject,
  LOCALE_ID }
  from '@angular/core';
  
@Component({
selector: 'app-root',
templateUrl: './app.component.html'
})
export class AppComponent {
curr = formatDate("02-february-0202", 'dd-MM-yyyy' ,this.locale);
constructor(
  @Inject(LOCALE_ID) public locale: string,){}
}


app.component.html




<h1>
  GeeksforGeeks
</h1>
  
<p>Locale Date is : {{curr}}</p>


Output:

Example 2:

app.component.ts




import {
  formatDate
 }
  from '@angular/common';
  
import {Component,
  Inject,
  LOCALE_ID }
  from '@angular/core';
  
@Component({
selector: 'app-root',
templateUrl: './app.component.html'
})
export class AppComponent {
curr = formatDate("03-march-0303", 'yyyy-dd-MM' ,this.locale);
constructor(
  @Inject(LOCALE_ID) public locale: string,){}
}


app.component.html




<h1>
  GeeksforGeeks
</h1>
  
<p>Locale Date is : {{curr}}</p>


Output:

Reference: https://angular.io/api/common/formatDate



Last Updated : 28 Nov, 2022
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads