Thursday, November 21, 2019

Angular 7 Date Format DatePipe Example

DatePipe - Formats a date value according to locale rules. 
For Updating date format we are using DatePipe from '@angular/common' and then use the below code.
Angular 7 Date Format DatePipe Example

You have to pass the locale string as an argument to DatePipe.
  var ddMMyyyy = this.datePipe.transform(new Date(),"dd-MM-yyyy");
Pre-defined format options:
1.      'short': equivalent to 'M/d/yy, h:mm a' (6/15/15, 9:03 AM).
2.      'medium': equivalent to 'MMM d, y, h:mm:ss a' (Jun 15, 2015, 9:03:01 AM).
3.      'long': equivalent to 'MMMM d, y, h:mm:ss a z' (June 15, 2015 at 9:03:01 AM GMT+1).
4.      'full': equivalent to 'EEEE, MMMM d, y, h:mm:ss a zzzz' (Monday, June 15, 2015 at 9:03:01 AM GMT+01:00).
5.      'shortDate': equivalent to 'M/d/yy' (6/15/15).
6.      'mediumDate': equivalent to 'MMM d, y' (Jun 15, 2015).
7.      'longDate': equivalent to 'MMMM d, y' (June 15, 2015).
8.      'fullDate': equivalent to 'EEEE, MMMM d, y' (Monday, June 15, 2015).
9.      'shortTime': equivalent to 'h:mm a' (9:03 AM).
10. 'mediumTime': equivalent to 'h:mm:ss a' (9:03:01 AM).
11. 'longTime': equivalent to 'h:mm:ss a z' (9:03:01 AM GMT+1).
12. 'fullTime': equivalent to 'h:mm:ss a zzzz' (9:03:01 AM GMT+01:00).

Example:- In the first step, import DatePipe from '@angular/common' in the “app.module.ts” file.
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import {DatePipe} from '@angular/common';
@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule
  ],
  providers: [
    DatePipe
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }
Import DatePipe in your components and construct it and it looks like.

import { Component, OnInit } from '@angular/core';
import { HttpClient, HttpHeaders} from  '@angular/common/http';
import { DatePipe } from '@angular/common';
@Component({
  selector: 'Calr',
  templateUrl: './calr.component.html',
  styleUrls: ['./calr.component.css']
})
export class CalrComponent implements OnInit {
  constructor(private datePipe: DatePipe)
              {   }
  ngOnInit() {
    var ddMMyyyy = this.datePipe.transform(new Date(),"dd-MM-yyyy");
    console.log(ddMMyyyy); //output - 14-02-2019
    var MMddyyyy = this.datePipe.transform(new Date(),"MM-dd-yyyy");
    console.log(MMddyyyy); //output - 14-02-2019
    var short = this.datePipe.transform(new Date(),"M/d/yy");
    console.log(short); //output - 2/14/19
    var medium = this.datePipe.transform(new Date(),"MMM d, y, h:mm:ss a");
    console.log(medium); //output - Feb 14, 2019, 3:45:06 PM
  }
  onSubmit(){
    this.model.NextDate = this.datePipe.transform(this.model.NextDate,"dd-MM-yyyy");
    alert(JSON.stringify(this.model));
  }
}
you can see : custom datepicker in angular 

No comments:

Post a Comment