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

Angular 2中使用Formly能否修改input date格式为YYYY-MM-DD?

Absolutely feasible! Let's break this down based on what you actually need—whether you want the submitted value to be in YYYY-MM-DD format, or you need the displayed format in the input to force that pattern (since native date inputs behave differently based on the user's system locale).

1. If you just need the submitted value to be YYYY-MM-DD (already covered!)

The native HTML5 type="date" input that Formly uses here automatically formats the submitted value as YYYY-MM-DD, no matter how it's displayed to the user. Browsers will show the date in the user's local format (like MM/DD/YYYY for US users or DD/MM/YYYY for EU users), but when you access form.value.registerDate, it will always be in YYYY-MM-DD format.

Your existing code already handles this case—no changes needed!

2. If you need the displayed input to force YYYY-MM-DD (override locale)

Native date inputs don't let you force a display format directly. To make the input show YYYY-MM-DD for all users, you'll need to create a custom Formly type using a text input and a date formatting library like date-fns (lightweight and tree-shakable). Here's a step-by-step implementation:

Step 1: Install a date formatting library

npm install date-fns

Step 2: Create a custom Formly field component

import { Component } from '@angular/core';
import { FieldType, FieldTypeConfig } from '@ngx-formly/core';
import { format, parse, isDate } from 'date-fns';

@Component({
  selector: 'formly-custom-date-input',
  template: `
    <input 
      type="text" 
      [formControl]="formControl" 
      [formlyAttributes]="field"
      (blur)="formatDate()"
      placeholder="YYYY-MM-DD"
      class="form-control"
    />
  `,
})
export class CustomDateInputComponent extends FieldType<FieldTypeConfig> {
  formatDate() {
    const value = this.formControl.value;
    if (!value) return;

    // Parse input and format to YYYY-MM-DD
    const parsedDate = parse(value, 'yyyy-MM-dd', new Date());
    if (isDate(parsedDate) && !isNaN(parsedDate.getTime())) {
      this.formControl.setValue(format(parsedDate, 'yyyy-MM-dd'), { emitEvent: false });
    } else {
      // Mark invalid dates for validation
      this.formControl.setErrors({ invalidDate: 'Please enter a valid date in YYYY-MM-DD format' });
    }
  }
}

Step 3: Register the custom type in your module

import { NgModule } from '@angular/core';
import { FormlyModule } from '@ngx-formly/core';
import { CustomDateInputComponent } from './custom-date-input.component';

@NgModule({
  imports: [
    FormlyModule.forRoot({
      types: [
        {
          name: 'custom-date',
          component: CustomDateInputComponent,
        },
      ],
    }),
  ],
  declarations: [CustomDateInputComponent],
})
export class AppModule {}

Step 4: Update your Formly config to use the custom type

{ 
  className: 'col-4', 
  type: 'custom-date', // Replace 'input' with your custom type
  key: 'registerDate', 
  templateOptions: { 
    label: 'Date 1', 
    placeholder: 'YYYY-MM-DD'
  } 
}

Alternative: Use Formly hooks without a custom component

If you don't want to create a separate component, you can use Formly's hooks to format the value on the fly:

{ 
  className: 'col-4', 
  type: 'input', 
  key: 'registerDate', 
  templateOptions: { 
    type: 'text', // Switch to text input
    label: 'Date 1', 
    placeholder: 'YYYY-MM-DD'
  },
  hooks: {
    onInit: (field) => {
      field.formControl.valueChanges.subscribe((value) => {
        if (value) {
          const parsedDate = parse(value, 'yyyy-MM-dd', new Date());
          if (isDate(parsedDate) && !isNaN(parsedDate.getTime())) {
            field.formControl.setValue(format(parsedDate, 'yyyy-MM-dd'), { emitEvent: false });
          }
        }
      });
    }
  }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 03:29:37