SaturnTeam / saturn-datepicker

Angular Material Datepicker with range selection
MIT License
278 stars 110 forks source link

How to create a custom DateAdapter? #128

Closed TheNemus closed 4 years ago

TheNemus commented 4 years ago

env: @angular/core 9.0.1 @angular/cli 9.0.1

Hi, I want to have back an ISO8601 string date from saturn-dp. I followed this tutorial working-with-custom-dateadapter-for-angular-material-2-datepicker

but my adapter is not even called:

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

// extend NativeDateAdapter's format method to specify the date format.
//
export class ISODateAdapter extends NativeDateAdapter {
   format(date: Date, displayFormat: Object): string {
      if (displayFormat === 'input') {
         const day = date.getUTCDate();
         const month = date.getUTCMonth() + 1;
         const year = date.getFullYear();
         // Return the format as per your requirement
         return `${day}-${month}-${year}`;
      } else {
         return date.toISOString();
      }
   }

   // If required extend other NativeDateAdapter methods.
}

Module:

// Custom DateAdapter
import { NgModule } from '@angular/core';
import { MatDatepickerModule } from '@angular/material/datepicker';
import { NativeDateModule, MAT_DATE_FORMATS, DateAdapter } from '@angular/material/core';
import { ISODateAdapter } from './iso-date-adapter';

const MY_DATE_FORMATS = {
  parse: {
     dateInput: {month: 'short', year: 'numeric', day: 'numeric'}
  },
  display: {
     dateInput: 'input',
     monthYearLabel: {year: 'numeric', month: 'short'},
     dateA11yLabel: {year: 'numeric', month: 'long', day: 'numeric'},
     monthYearA11yLabel: {year: 'numeric', month: 'long'},
  }
};
@NgModule({
  declarations: [],
  imports: [],
  exports: [MatDatepickerModule, NativeDateModule],
  providers: [
     {
        provide: DateAdapter, useClass: ISODateAdapter
     },
     {
        provide: MAT_DATE_FORMATS, useValue: MY_DATE_FORMATS
     }
  ]
})
export class ISODateAdapterModule {}

injected in my feature module.

What am I missing?

SaturnTeam commented 4 years ago

Please try to import MAT_DATE_FORMATS from saturn-datepicker

TheNemus commented 4 years ago

Could you be a little more clear? Import where? To use in which way?

SaturnTeam commented 4 years ago

@TheNemus instead of import { NativeDateModule, MAT_DATE_FORMATS, DateAdapter } from '@angular/material/core'; try to import { NativeDateModule, MAT_DATE_FORMATS, DateAdapter } from 'saturn-datepicker';

TheNemus commented 4 years ago

Thamk you, now the IsoDateAdapteris being called.

Last question is: what method I have to re-implement in order to get an ISO8601 date in the model?Cause the formatmethod only change the way the date is displayed.

SaturnTeam commented 4 years ago

model operates with the JS Date object. You can the method .toISOString()