'Angular 8 - How to format date in saturn-datepicker

I want to show the date format like as yyyy-mm-dd. I installed package saturn-datepicker but I don't know how to change the format. Could you help me to show the way to change the date format?



Solution 1:[1]

Solution 1: With @angular/material-moment-adapter

Step 1: Install @angular/material-moment-adapter.

npm install @angular/material-moment-adapter

Step 2:

  1. Import constants from saturn-datepicker.
  2. Define your date format.

app.module.ts

import {
  MAT_DATE_FORMATS,
  DateAdapter,
  MAT_DATE_LOCALE
} from 'saturn-datepicker';
import { MomentDateAdapter } from '@angular/material-moment-adapter';

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

@NgModule({
  ...
  providers: [
    {
      provide: DateAdapter,
      useClass: MomentDateAdapter,
      deps: [MAT_DATE_LOCALE]
    },
    { provide: MAT_DATE_FORMATS, useValue: MY_FORMATS }
  ]
})
export class AppModule {}

Sample Solution 1 on StackBlitz


Solution 2: With build your own DateAdapter

Step 1: Create custom AppDateAdapter.

date.adapter.ts

import { NativeDateAdapter } from "@angular/material/core";


export class AppDateAdapter extends NativeDateAdapter {

    format(date: Date, displayFormat: Object): string {
        var d = new Date(date),
        month = '' + (d.getMonth() + 1),
        day = '' + d.getDate(),
        year = d.getFullYear();

        if (month.length < 2) 
            month = '0' + month;
        if (day.length < 2) 
            day = '0' + day;

        return [year, month, day].join('-');
    }
}

Step 2:

  1. Import AppDateAdapter into providers section.
  2. Define your date format.

app.module.ts

import { MAT_DATE_FORMATS, DateAdapter } from 'saturn-datepicker';
import { AppDateAdapter } from './date.adapter';

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

@NgModule({
  ...
  providers: [
     { provide: DateAdapter, useClass: AppDateAdapter },
     { provide: MAT_DATE_FORMATS, useValue: MY_FORMATS }
  ]
})
export class AppModule {}

Sample solution 2 on StackBlitz


Reference

How to change date format or locale?

Solution 2:[2]

If you do not want to build your own adapter, try this demo (with masking)

https://stackblitz.com/edit/angular-material-date-5srxwu?file=src/app/app.component.html enter image description here

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Yong Shun
Solution 2 Yiping