【问题标题】:Configure moment custom date adapter配置时刻自定义日期适配器
【发布时间】:2020-01-29 06:50:16
【问题描述】:

我使用了时刻日期适配器。所以我面临的主要问题是每当我输入像 56 年 1 月 12 日这样的日期并且在按下制表符后它会自动更正为 2056 而不是 1956 年。只有当我输入 69-99 时它才会显示正确的年份并且它会更改为“ 19"

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

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

【问题讨论】:

    标签: angular momentjs


    【解决方案1】:

    看看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

    【讨论】:

    • 但是添加这个解析函数后我得到一个简单的错误“错误类型错误:date.clone 不是函数”你知道如何解决这个问题
    • 在我的 stackblitz 中不会发生.. 如果您收到 data.clone,请检查您写“date.clone”的位置,并确保日期不为空 if (date){ date.clone()}
    猜你喜欢
    • 1970-01-01
    • 2018-12-31
    • 2010-12-13
    • 1970-01-01
    • 2023-03-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多