How to change ngbDatepicker date format from JSON to YYYY/MM/DD

There two important class to manage ngbDate. one it’s for formatting the date: a DateParserFormater, and another to change the value you get/send from/to a ngb-datepicker: a DateAdapter.

So, you can create a customDateAdapter and a customDateParserFormatter. But, don’t worry about the names. ist only two injectable class like, e.g.

For customDateAdapter

@Injectable()
export class CustomDateAdapter {
  fromModel(value: string): NgbDateStruct
  {
     if (!value)
      return null
     let parts=value.split("https://stackoverflow.com/");
     return {year:+parts[0],month:+parts[1],day:+parts[2]}
  }

  toModel(date: NgbDateStruct): string // from internal model -> your mode
  {
    return date?date.year+"https://stackoverflow.com/"+('0'+date.month).slice(-2)
           +"https://stackoverflow.com/"+('0'+date.day).slice(-2):null
  }
}

Yes a injectable class with two functions, one to transform a NgbDate to string and another to transform string to NgbDate. remember that this change your “model”

For CustomDateParserFormatter

@Injectable()
export class CustomDateParserFormatter {
  parse(value: string): NgbDateStruct
  {
    if (!value)
      return null
     let parts=value.split("https://stackoverflow.com/");
     return {year:+parts[0],month:+parts[1],day:+parts[2]} as NgbDateStruct

  }
  format(date: NgbDateStruct): string
  {
    return date?date.year+"https://stackoverflow.com/"+('0'+date.month).slice(-2)+"https://stackoverflow.com/"+('0'+date.day).slice(-2):null
  }
}

Again an injectable class with two functions, one to transform a NgbDate to string and another to transform string to NgbDate. Remember that this change the “format” of the date -useful if you want, e.g. dd/MM/yyyy-

Then just add as providers in your component

  providers: [{provide: NgbDateAdapter, useClass: CustomDateAdapter},
              {provide: NgbDateParserFormatter, useClass: CustomDateParserFormatter}]

In the stackblitz see the definition of component, you can choose, e.g.

@Component({
  selector: 'ngbd-datepicker-adapter',
  templateUrl: './datepicker-adapter.html',
  providers: [{provide: NgbDateAdapter, useClass: NgbDateNativeAdapter}]
})

or

@Component({
  selector: 'ngbd-datepicker-adapter',
  templateUrl: './datepicker-adapter.html',
  providers: [{provide: NgbDateAdapter, useClass: CustomDateAdapter},
          {provide: NgbDateParserFormatter, useClass: CustomDateParserFormatter}]
})

even you can write

@Component({
  selector: 'ngbd-datepicker-adapter',
  templateUrl: './datepicker-adapter.html',
  providers: [{provide: NgbDateParserFormatter, useClass: CustomDateParserFormatter}]
})

To manteinance the objects like {year,month,day}, but change the “mask” -and the way you input the date

NOTE: You can add the providers to the module too

Leave a Comment