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

时间:2019-03-12 10:09:42

标签: javascript angular typescript date

嗨,我正在使用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>

这是我的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);
    }
  }

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

2 个答案:

答案 0 :(得分:1)

您需要扩展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 "";
  }
}

修改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 {}

答案 1 :(得分:0)

完美的解决方案是更改下面的文件,我已经编辑了代码以在输入字段中获得所需的格式(DD-MM-YYYY)。

  

ngb-date-parser-formatter.js

从下面的代码中,您将在输入字段中获得 DD-MM-YYYY 日期格式。

var __extends = (this && this.__extends) || function (d, b) {
    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
    function __() { this.constructor = d; }
    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
import { padNumber, toInteger, isNumber } from '../util/util';
/**
 * Abstract type serving as a DI token for the service parsing and formatting dates for the NgbInputDatepicker
 * directive. A default implementation using the ISO 8601 format is provided, but you can provide another implementation
 * to use an alternative format.
 */
var NgbDateParserFormatter = (function () {
    function NgbDateParserFormatter() {
    }
    return NgbDateParserFormatter;
}());
export { NgbDateParserFormatter };
var NgbDateISOParserFormatter = (function (_super) {
    __extends(NgbDateISOParserFormatter, _super);
    function NgbDateISOParserFormatter() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    NgbDateISOParserFormatter.prototype.parse = function (value) {
        if (value) {
            var dateParts = value.trim().split('-');
            if (dateParts.length === 1 && isNumber(dateParts[0])) {
                return { year: toInteger(dateParts[0]), month: null, day: null };
            }
            else if (dateParts.length === 2 && isNumber(dateParts[0]) && isNumber(dateParts[1])) {
                return { year: toInteger(dateParts[0]), month: toInteger(dateParts[1]), day: null };
            }
            else if (dateParts.length === 3 && isNumber(dateParts[0]) && isNumber(dateParts[1]) && isNumber(dateParts[2])) {
                return { year: toInteger(dateParts[0]), month: toInteger(dateParts[1]), day: toInteger(dateParts[2]) };
            }
        }
        return null;
    };
    NgbDateISOParserFormatter.prototype.format = function (date) {
        return date ?
        (isNumber(date.day) ? padNumber(date.day) : '')+"-"+ (isNumber(date.month) ? padNumber(date.month) : '') +"-"+ date.year:'';
    };
    return NgbDateISOParserFormatter;
}(NgbDateParserFormatter));
export { NgbDateISOParserFormatter };
//# sourceMappingURL=ngb-date-parser-formatter.js.map