How to format date with Angular material datetime picker

I am searching a lot on google. But I have the material datetime picker. So not the date picker, but the datetime picker. And I want to format the date-time , like in this format:

2021-02-15 23:59:59

But I try to do it without moment.js. Because it is not good practice. But if it can’t be done without moment.js then be it.

So I have this js file:

const CUSTOM_DATE_FORMATS: NgxMatDateFormats = {
  parse: {
    dateInput: ''
  },
  display: {
    dateInput: 'YYYY-MM-DD HH:mm:ss',
    monthYearLabel: 'MMM YYYY',
    dateA11yLabel: 'LL',
    monthYearA11yLabel: 'MMMM YYYY',
  }
};
@Component({
  selector: 'app-widget-editor',
  templateUrl: './widget-editor.component.html',
  styleUrls: ['./widget-editor.component.css'],
  providers: [
    {provide: DateAdapter, useClass: AppDateAdapter},
    {provide: MAT_DATE_FORMATS, useValue: APP_DATE_FORMATS}

  ]
})
export class WidgetEditorComponent implements OnInit, AfterContentInit {
  @ViewChild('picker') picker;

 
  start: string;
  end: string;
  interval: string;
  duration: string;
  yrange: number[]; 

  constructor(private editorService: EditorService ) {} 

  reOpenCalender() {
    let self = this;
    setTimeout(() => {
      self.picker.open();
    } );
  }  
}

and this is template:

  <div class="form-group row">
                <label for="start" class="editor-label col-sm-4"><strong> Time start:</strong></label>

                <input [(ngModel)]="start" format  [ngModelOptions]="{standalone: true}" type="text" class="date"  id="start" value="start"  matInput [ngxMatDatetimePicker]="picker">
                <ngx-mat-datetime-picker #picker></ngx-mat-datetime-picker>


                <span class="ml-2" (click)= "reOpenCalender()">
                    <fa-icon [icon]="faCalendarAlt" size="1x"    #picker [styles]="{'color': '#B7B7B7'}"
                      ></fa-icon>
                </span>
            </div>

But the format is still like this:

2/16/2021, 04:36:32

and not in this format:

2021-02-15 23:59:59

So what I have to change?

Thank you

1 thought on “How to format date with Angular material datetime picker”

Leave a Comment