How to customize date format as 'YYYY-MM-DD HH:mm:ss'?

5.2k views Asked by At

Returning Moment object instead of Date value in 'YYYY-MM-DD HH:mm:ss' format

I tried the following but getting moment object instead of Date. I searched a lot but none of them give me the solution.

import * as _moment from 'moment';
import { default as _rollupMoment } from 'moment';
const moment = _rollupMoment || _moment;

export const MY_FORMATS = {
    parse: {
        dateInput: 'YYYY-MM-DD HH:mm:ss',
    },
    display: {
        dateInput: 'YYYY-MM-DD HH:mm:ss',
        monthYearLabel: 'MMM YYYY',
        dateA11yLabel: 'YYYY-MM-DD HH:mm:ss',
        monthYearA11yLabel: 'MMMM YYYY',
    },
};
  

I provided the format inside @Component decorator

@Component({
     providers: [
    {
      provide: DateAdapter,
      useClass: MomentDateAdapter,
      deps: [MAT_DATE_LOCALE, MAT_MOMENT_DATE_ADAPTER_OPTIONS]
    },
    { provide: MAT_DATE_FORMATS, useValue: MY_FORMATS },
  ]
})

Inside Class =>

 dateOfBirth: new FormControl();
2

There are 2 answers

3
Murugan On

try this code.

import { DatePipe, formatDate } from '@angular/common';
import { Component, OnInit, ElementRef, ViewChild, ViewEncapsulation } from '@angular/core';
import { FormBuilder, FormGroup, FormControl, Validators } from '@angular/forms';

export class UserRegistrationComponent implements OnInit {
dateOfBirth: new FormControl();

constructor(private datePipe: DatePipe){

}

save(){
    this.datePipe.transform(this.dateOfBirth.value, "yyyy-MM-dd HH:mm:ss");
}
}
2
Murugan On

Add the below code in your application.

app.module.ts

 import { DateAdapter, MAT_DATE_FORMATS, MAT_DATE_LOCALE } from '@angular/material/core';
    import { MomentDateModule, MomentDateAdapter } from '@angular/material-moment-adapter';
    import { DatePipe } from '@angular/common';
    
    export const DateFormats = {
        parse: {
            dateInput: 'YYYY-MM-DD HH:mm:ss',
        },
        display: {
            dateInput: 'YYYY-MM-DD HH:mm:ss',
            monthYearLabel: 'MMM YYYY',
            dateA11yLabel: 'YYYY-MM-DD HH:mm:ss',
            monthYearA11yLabel: 'MMMM YYYY',
        },
    };
    
    
    providers: [
        { provide: DateAdapter, useClass: MomentDateAdapter, deps: [MAT_DATE_LOCALE] },
        { provide: MAT_DATE_FORMATS, useValue: DateFormats }
        , DatePipe
    ],

*.components,ts

dateOfBirth: new FormControl();

If you add the above code in your project correctly, you get all the mat date picker date value in this format YYYY-MM-DD HH:mm: ss