简体   繁体   English

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

[英]how to change NgbDatePicker format from YYYY-MM-DD to MM-DD-YYYY angular 4?

hi i am using ngbDatePicker and my format is YYYY-MM-DD and i am trying to change it but cant seem to change the format to MM/DD/YYYY. 嗨,我正在使用ngbDatePicker,我的格式是YYYY-MM-DD,我正在尝试更改它,但似乎无法将格式更改为MM / DD / YYYY。

here is my html code 这是我的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>

here is my ts file code 这是我的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);
    }
  }

i cannot seem to find any help to change the format. 我似乎找不到改变格式的任何帮助。 how can i change the format from YYYY/DD/MM toMM/DD/YYYY. 如何将格式从YYYY / DD / MM更改为MM / DD / YYYY。 is there any help thanks 有什么帮助吗谢谢

You need to extend NgbDateParserFormatter and override the default provider: 您需要扩展NgbDateParserFormatter并覆盖默认提供程序:

Below is an example for dd/mm/yyyy, you'll just need to alter the parse() and format() functions to change to mm/dd/yyyy. 以下是dd / mm / yyyy的示例,您只需要更改parse()format()函数即可将其更改为mm / dd / yyyy。

Add the following class: 添加以下类:

 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 ""; } } 

Modify app.module.ts to override the default provider: 修改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 {} 

The perfect solution would be to alter the file below, I have edited the code to get the required format(DD-MM-YYYY) in my input field. 完美的解决方案是更改下面的文件,我已经编辑了代码以在输入字段中获得所需的格式(DD-MM-YYYY)。

ngb-date-parser-formatter.js NGB最新的解析器,formatter.js

from the code below you will get DD-MM-YYYY Date format in input filed. 从下面的代码中,您将在输入字段中获得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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM