如何将 NgbDatePicker 格式从 YYYY-MM-DD 更改为 MM-DD-YYYY angular 4?

8 javascript date typescript angular

嗨,我正在使用 ngbDatePicker,我的格式是 YYYY-MM-DD,我正在尝试更改它,但似乎无法将格式更改为 MM/DD/YYYY。

这是我的 html 代码

    <div class="form-group datepicker">
      <label for="dob">Date of Birth*</label>
      <div class="row input-group">
        <input
          ngbDatepicker
          #d="ngbDatepicker"
          #dobF="ngModel"
          class="form-control input-underline input-lg"
          id="dob"
          [(ngModel)]="dateOfBirth"
          placeholder="mm-dd-yyyy"
          name="dp"
          [ngClass]="{
            invalid:
              (dobF.value === null || isString(dobF.value) || futureDate) && dobF.touched
          }"
          required
        />
        <div class="input-group-append">
          <button
            class="btn btn-outline-secondary calendar"
            (click)="d.toggle()"
            type="button"
          ></button>
        </div>
      </div>
      <div
        *ngIf="
          (dobF.value === null || isString(dobF.value)  || futureDate) && dobF.touched
        "
        class="error"
      >
        Please enter a valid date of birth.
      </div>
    </div>
Run Code Online (Sandbox Code Playgroud)

这是我的 ts 文件代码

  public dateOfBirth: { year: number; month: number; day: number };

  public currentDate = moment().format("YYYY-MM-DD");



constructor(
private config: NgbDatepickerConfig
 ) {
// customize default values of datepickers used by this component tree
const currentDate = new Date();
  const day = currentDate.getDate();
   const month = currentDate.getMonth() + 1;
  const year = currentDate.getFullYear();

 this.config.minDate = {year: 1900, month: 1, day: 1};
 this.config.maxDate = {year, month, day};

 this.config.outsideDays = "hidden";
}

ngOninit() {

  this.subscriptions["patient"] = this.store
   .select("patient")
   .subscribe(data => {
    this.patient = Object.assign({}, this.patient, data);
    const dob = this.patient.Dob ? this.patient.Dob.split("-") : null;
    dob !== null
      ? (this.dateOfBirth = {
        year: Number(dob[0]),
        month: Number(dob[1]),
        day: Number(dob[2])
      })
      : (this.dateOfBirth = null);
  });
 }

ngAfterContentChecked() {
let currentDateObject = this.currentDate.split("-");
this.dobYear = Number(currentDateObject[0]);
this.dobMonth = Number(currentDateObject[1]);
this.dobDay = Number(currentDateObject[2]);
if (this.dateOfBirth) {
  this.futureDate = this.dateOfBirth.year > this.dobYear || (this.dateOfBirth.year == this.dobYear && this.dateOfBirth.month > this.dobMonth)
    || (this.dateOfBirth.year == this.dobYear && this.dateOfBirth.month == this.dobMonth && this.dateOfBirth.day > this.dobDay);
    }
  }
Run Code Online (Sandbox Code Playgroud)

我似乎找不到任何帮助来更改格式。如何将格式从 YYYY/DD/MM 更改为 MM/DD/YYYY。有什么帮助吗谢谢

Lia*_*ing 13

您需要扩展 NgbDateParserFormatter 并覆盖默认提供程序:

下面是 dd/mm/yyyy 的示例,您只需要更改parse()format()函数即可更改为 mm/dd/yyyy。

添加以下类:

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

@Injectable()
export class NgbDateCustomParserFormatter extends NgbDateParserFormatter {
  parse(value: string): NgbDateStruct {
    if (value) {
      const dateParts = value.trim().split("/");
      if (dateParts.length === 1 && isNumber(dateParts[0])) {
        return { day: toInteger(dateParts[0]), month: null, year: null };
      } else if (dateParts.length === 2 && isNumber(dateParts[0]) && isNumber(dateParts[1])) {
        return {
          day: toInteger(dateParts[0]),
          month: toInteger(dateParts[1]),
          year: null
        };
      } else if (dateParts.length === 3 && isNumber(dateParts[0]) && isNumber(dateParts[1]) && isNumber(dateParts[2])) {
        return {
          day: toInteger(dateParts[0]),
          month: toInteger(dateParts[1]),
          year: toInteger(dateParts[2])
        };
      }
    }
    return null;
  }

  format(date: NgbDateStruct): string {
    return date
      ? `${isNumber(date.day) ? padNumber(date.day) : ""}/${isNumber(date.month) ? padNumber(date.month) : ""}/${
          date.year
        }`
      : "";
  }
}
export function toInteger(value: any): number {
  return parseInt(`${value}`, 10);
}

export function isNumber(value: any): value is number {
  return !isNaN(toInteger(value));
}

export function padNumber(value: number) {
  if (isNumber(value)) {
    return `0${value}`.slice(-2);
  } else {
    return "";
  }
}
Run Code Online (Sandbox Code Playgroud)

修改 app.module.ts 以覆盖默认提供程序:

import { NgbDateCustomParserFormatter } from "./YOURPATH/date-formatter.service";

@NgModule({
  declarations: [
    ...
  ],
  imports: [
    ...
  ],
  providers: [
    ... , 
    { provide: NgbDateParserFormatter, useClass: NgbDateCustomParserFormatter }  // <-- add this
  ],
  bootstrap: [AppComponent]
})
export class AppModule {}
Run Code Online (Sandbox Code Playgroud)

  • 这与简单地输入所需的日期格式相比是一个荒谬的倒退。(这是针对图书馆的,不是针对你的) (2认同)