ngb-datepicker(ng Bootstrap) Display Day with Date

2019-08-24 03:57发布

问题:

Demo Code: https://stackblitz.com/edit/angular-bife8z?file=app%2Fdatepicker-basic.html

i want to Display my selected date like "Sunday, 23/12/18" Format is "Day, DD/MMM/YY"

回答1:

you need convert your model (is a NgbDateStruct) in a Date of JavaScript.

<ngb-datepicker #dp [(ngModel)]="model" 
     (ngModelChange)="dateJs=toDateJs($event);
                      dateString=toDateString($event)">
</ngb-datepicker>

<hr/>

<div class="my-3">
  Selected Date is: 
  <b>{{ model.day }}/{{ model.month }}/{{ model.year }}</b><br/>
  <b>{{dateJs |date:'EEE,dd/MM/yyyy'}}</b><br/>
  <b>{{dateString}}</b>
</div>

//don't forget import DatePipe
import {DatePipe} from '@angular/common'

@Component({
})
export class NgbdDatepickerBasic {
  /three variables
  model: NgbDateStruct;  //the model as NgbDateStruct
  dateJs:any;  //dateJs will be a Date object of javascript
  dateString:string;  //a string

  ngOnInit(){
    this.selectToday();
  }
  constructor(private calendar: NgbCalendar) {
  }
  //This function convert NgbDateStruct to Date object
  toDateJs(date: NgbDateStruct): Date {
    return date ? 
      new Date(Date.UTC(date.year,date.month-1,date.day,0,0,0)) : null;
  }
  //This function convert NgbDateStruct to string
  toDateString(date:NgbDateStruct)
  { 
    //The DatePipe need as argument the "locale"
    return date?  new DatePipe('en-US').transform(
      new Date(Date.UTC(date.year, date.month - 1, date.day, 0, 0, 0)),
      'EEE,dd/MM/yyyy')
    :null;
  }
  selectToday() {
    this.model = this.calendar.getToday();
    this.dateJs=this.toDateJs(this.model);
    this.dateString=this.toDateString(this.model);
  }
}

NOTE:I used the pipe date of angular, see the options: the options