You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过Angular Material的Date-Fns Adapter解析无分隔符短日期并映射两位年份?

解决Angular Material Date-Fns Adapter解析两位年份短日期的问题

问题背景

需要用Angular Material的Date-Fns Adapter解析无分隔符的短日期(如010123)为01.01.2023,但使用ddMMyy格式时,默认解析会将年份识别为0023而非2023,长格式01012023已能正常解析。当前自定义格式配置如下:

export const CUSTOM_FORMAT: MatDateFormats = {
  parse: {
    dateInput: ["dd.MM.yyyy", "dd/MM/yyyy", "dd,MM,yyyy", "ddMMyyyy", "ddMMyy"],
  },
  display: {
    dateInput: "dd.MM.yyyy",
    monthYearLabel: "MMM yyyy",
    dateA11yLabel: "MMMM d, y",
    monthYearA11yLabel: "MMM yyyy"
  },
};

解决方案

默认的ddMMyy格式遵循Unicode规范,仅取两位年份补零,因此需要自定义Date-Fns适配器的解析逻辑,手动将两位年份映射到目标世纪(如2000-2099)。

步骤1:创建自定义Date-Fns适配器

继承MatDateFnsAdapter,重写parse方法,针对6位无分隔符字符串做特殊处理:

import { Injectable } from '@angular/core';
import { MatDateFnsAdapter } from '@angular/material-date-fns-adapter';
import { isValid } from 'date-fns';

@Injectable()
export class CustomDateFnsAdapter extends MatDateFnsAdapter {
  parse(value: any, parseFormat: string | string[]): Date | null {
    // 拦截6位无分隔符的短日期(ddMMyy格式)
    if (typeof value === 'string' && value.length === 6) {
      const day = parseInt(value.slice(0, 2), 10);
      const month = parseInt(value.slice(2, 4), 10) - 1; // date-fns月份从0开始计数
      let year = parseInt(value.slice(4, 6), 10);

      // 将两位年份映射到2000-2099区间,可根据需求调整规则
      year += 2000;

      const parsedDate = new Date(year, month, day);
      // 验证日期有效性,避免无效日期如31.04.2023
      if (isValid(parsedDate) && 
          parsedDate.getDate() === day && 
          parsedDate.getMonth() === month && 
          parsedDate.getFullYear() === year) {
        return parsedDate;
      }
    }

    // 其他格式沿用默认解析逻辑
    return super.parse(value, parseFormat);
  }
}

步骤2:配置模块使用自定义适配器

在你的日期选择器模块中,替换默认的DateAdapter并传入自定义格式:

import { NgModule } from '@angular/core';
import { MatDatepickerModule } from '@angular/material/datepicker';
import { MatInputModule } from '@angular/material/input';
import { MAT_DATE_FORMATS, DateAdapter } from '@angular/material/core';
import { CustomDateFnsAdapter } from './custom-date-fns-adapter';
import { CUSTOM_FORMAT } from './date-formats';

@NgModule({
  imports: [MatDatepickerModule, MatInputModule],
  providers: [
    { provide: DateAdapter, useClass: CustomDateFnsAdapter },
    { provide: MAT_DATE_FORMATS, useValue: CUSTOM_FORMAT }
  ]
})
export class CustomDatepickerModule { }

可选调整

如果需要更灵活的年份映射规则(如00-69对应2000-2069,70-99对应1970-1999),可修改年份映射逻辑:

year = year <= 69 ? year + 2000 : year + 1900;

内容的提问来源于stack exchange,提问作者stax

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.05 21:47:11