NGB-日期选择器(NG自举)显示日与日期为DD / MMM / YY(实施例输出“星期日,23/1

2019-10-31 07:33发布

演示代码: https://stackblitz.com/edit/angular-bife8z?file=app%2Fdatepicker-basic.html

我要显示我选定的日期,如“周日23/12/18”格式为“天,DD / MMM / YY”

Answer 1:

你需要转换模型(是NgbDateStruct)在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);
  }
}

注:我用的角管日期,看到的选项: 选项



文章来源: ngb-datepicker(ng Bootstrap) Display Day with Date as DD/MMM/YY (Example output “Sunday, 23/12/18” )