7

I'm working with ngbDatepicker this is giving me JSON date format like:

{ year: 2019, month: 6, day: 9 }

How can I convert this into YYYY/MM/DD? I'm using Angular 7.

My Code is as below:

<div class="input-group">
   <input class="form-control" placeholder="YYYY-MM-DD"
          (click)="d2.toggle()" (ngModelChange)="onDateSelection($event,'ToDate');"  name="d2" #c2="ngModel" [(ngModel)]="toDate" ngbDatepicker #d2="ngbDatepicker">
         <div class="input-group-append">
          <button class="btn btn-outline-secondar" 
             (click)="d2.toggle()" type="button">
           <i class="fa fa-calendar" aria-hidden="true"></i>
          </button>
         </div>
 </div>
Kunal Dholiya
  • 335
  • 2
  • 6
  • 19

4 Answers4

13

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('/');
     return {year:+parts[0],month:+parts[1],day:+parts[2]}
  }

  toModel(date: NgbDateStruct): string // from internal model -> your mode
  {
    return date?date.year+"/"+('0'+date.month).slice(-2)
           +"/"+('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('/');
     return {year:+parts[0],month:+parts[1],day:+parts[2]} as NgbDateStruct

  }
  format(date: NgbDateStruct): string
  {
    return date?date.year+"/"+('0'+date.month).slice(-2)+"/"+('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

Eliseo
  • 50,109
  • 4
  • 29
  • 67
  • I want to clarify something. I have shared module in that module I have date picker component with some modification cause I wanted to select multiple days not the range of date. when I implemented this custom pipe will it automatically change the date formate to yyyy-mm-dd or should I call some function inside my component? since I'm working on a child module. should I put those custom class in my app.module.ts as well or only on my child.module.ts? – NicoleZ Aug 26 '19 at 13:10
3

Try the following line of code to reformat the date of the NgbDatepicker.

const date = object.year + '/' + object.month + '/'+ object.day
Graham John
  • 170
  • 12
sid
  • 365
  • 2
  • 11
1

if you are using date field you need to bind the model in ts. in the html, call the method dateselect like this

 (dateSelect)="onDateSelect($event)"

Full code:

 <input class="form-control"(dateSelect)="onDateSelect($event)"  id="TargetDate" placeholder="mm/dd/yyyy" name="targetDate" ngbDatepicker
          #date="ngbDatepicker"  />
          <div class="input-group-append">
            <button id="TargetDateButton" class="btn btn-outline-secondary" (click)="date.toggle()" type="button">
              <span class="oi oi-calendar"></span>
            </button>
          </div>

In the type script, use the following code.This is applicable only if you are using Ngbdate picker.

 onDateSelect(event) {
  let year = event.year;
  let month = event.month <= 9 ? '0' + event.month : event.month;;
  let day = event.day <= 9 ? '0' + event.day : event.day;;
  let finalDate = year + "-" + month + "-" + day;
 }
Venkatesh K
  • 133
  • 1
  • 1
  • 11
0

Follow the steps below to use the ngbDate Parser Formatter.

  1. Create a service called NgbDateCustomParserFormatter.
  2. Add the following code inside the service.

import {Injectable} from "@angular/core";
import {NgbDateParserFormatter, NgbDateStruct} from "@ng-bootstrap/ng-bootstrap";

@Injectable()
export class NgbDateCustomParserFormatter extends NgbDateParserFormatter {
  override parse(value: string): NgbDateStruct | null {
    return value ? {
      day : parseInt(value.substring(0, 2), 10),
      month : parseInt(value.substring(3, 5), 10),
      year : parseInt(value.substring(6, 10), 10)
    } : null;
  }

  override format(date: NgbDateStruct | null): string {
    return date ? `${date.day}-${date.month}-${date.year}` : '';
  }
}


  1. Import the following code into @ngModule of the datepicker module you added.
providers: [{provide: NgbDateParserFormatter, useClass: NgbDateCustomParserFormatter}],

NOTE: I set the date format to be DD-MM-YYYY. If you wish, you can change the format part of the code according to you.

  • 1
    As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Aug 23 '23 at 23:48