配置时刻自定义日期适配器

时间:2020-01-29 06:50:16

标签: angular momentjs

我使用了时刻日期适配器。因此,我面临的主要问题是每当我键入日期(如1/12/56),并按Tab后它会自动更正为2056(而不是1956)。每当我键入69-99时,它只会显示正确的年份,并且更改为“ 19“

enter image description here

我的自定义日期适配器代码是:

import { Inject, Injectable, Optional } from "@angular/core";
import { MAT_DATE_LOCALE } from "@angular/material";
import { MomentDateAdapter } from "@angular/material-moment-adapter";
import { Moment } from "moment";
import * as moment from "moment";

@Injectable()
export class MomentUtcDateAdapter extends MomentDateAdapter {
    constructor(@Optional() @Inject(MAT_DATE_LOCALE) dateLocale: string) {
        super(dateLocale);
    }

    createDate(year: number, month: number, date: number): Moment {
        return moment({ year, month, date });
    }
}

1 个答案:

答案 0 :(得分:2)

看看this answer in SO

您可以像这样更改解析功能

parse(value:string):any
   {
     let parts=value.replace(/\./g,'/').replace(/-/g,'/').split('/');
     let year=+parts[2]
     if (year<100) //if is less than 100
     {
       year=(year<56)?year+2000:year+1900 //sum 1900 or 2000 acording requeriment

     }
     if (parts.length==3)
      return new Date(year,(+parts[1])-1,+parts[0])

   }

请参阅stackblitz

相关问题