of-bootstrap 日期选择器格式

ng-bootstrap datepicker format

我正在使用 ng-bootstrap 日期选择器,但是当我保存表单时,日期被另存为。

date: {
  day: 01,
  month: 12,
  year: 16
}

我希望我能把它保存为更像 "2016-11-23T00:39:31.768Z"

的东西

这是我的实现:

<div class="input-group">
  <button class="input-group-btn" (click)="d.toggle()" >
    <md-icon svgSrc="assets/images/calendar-plus.svg" style="cursor: pointer;"></md-icon>
  </button>
  <input class="form-control" placeholder="dd-mm-yyyy" name="dp" formControlName="due_date" navigation="arrows" ngbDatepicker #d="ngbDatepicker">
</div>

和form.component:

constructor( private fb: FormBuilder ) {
    this.form = this.fb.group({
      due_date: [''],
    });
  }

您使用的是 ng-bootstrap 而不是 ng2-bootstrap (不同的组)。它背后的代码使用 NgbDateStruct 这是一个对象 { day, month, year }

提交时,您需要挂钩并将值更改为其他值,例如:

onSubmit(): {
    let ngbDate = this.form.controls['due_date'].value;
    let myDate = new Date(ngbDate.year, ngbDate.month-1, ngbDate.day);
    let formValues = this.form.value;
    formValues['due_date'] = myDate;
    <...>
    http.post(url, formValues);
}

https://ng-bootstrap.github.io/#/components/datepicker

NgbDateStruct Interface of the model of the NgbDatepicker and NgbInputDatepicker directives

Properties

day Type: number The day of month, starting at 1

month Type: number The month, with default calendar we use ISO 8601: 1=Jan ... 12=Dec

year Type: number The year, for example 2016

如@silentsod 所述,您需要将日期选择器使用的日期对象从 NgbDateStruct 格式转换为 string 格式。 ng-bootstrap提供了将NgbDateStruct格式的日期转换为ISO 8601格式的函数(yyyy-mm-dd)。如果使用该格式,则不必自己编写:

import {NgbDateParserFormatter} from '@ng-bootstrap/ng-bootstrap';

...

constructor(private ngbDateParserFormatter: NgbDateParserFormatter; ... ) {
    ...
}

...

onSubmit(): {
    let ngbDate = this.form.controls['due_date'].value;
    let myDate = this.ngbDateParserFormatter.format(ngbDate); // e.g. myDate = 2017-01-01
    ...
}

参见:https://github.com/ng-bootstrap/ng-bootstrap/blob/master/src/datepicker/ngb-date-parser-formatter.ts

您可以实现自己的方法将其转换为您需要的 DD-MM-YYYY 格式。

或者根据 return 语句中元素的顺序和分隔符,您可以创建您想要的任何其他格式。

实施:

formatDate(d: NgbDate): string {
  if (d === null) {
    return null;
  }

  return [
    (d.day < 10 ? ('0' + d.day) : d.day),
    (d.month < 10 ? ('0' + d.month) : d.month),
    d.year
  ].join('-');
}