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

Angular Material datetime-local输入框默认显示0001年1月,如何设为今日日期?

解决Angular Material datetime-local输入框默认显示今日日期的问题

问题出在你的ndate FormControl未设置初始值,导致datetime-local控件默认显示0001年1月。只需给FormControl设置符合要求的当前日期值即可,具体实现如下:

方法一:初始化FormControl时直接赋值

在组件的TypeScript文件中,创建FormControl时传入格式化后的当前日期:

import { FormControl } from '@angular/forms';

@Component({
  // 你的组件元数据(如selector、templateUrl等)
})
export class YourComponent {
  // 将当前日期格式化为datetime-local要求的YYYY-MM-DDTHH:mm格式
  ndate = new FormControl(new Date().toISOString().slice(0, 16));
}

方法二:在组件初始化后赋值

如果需要在组件生命周期钩子中设置(比如依赖其他数据加载完成后),可以在ngOnInit中用setValue方法:

import { FormControl, OnInit } from '@angular/forms';

@Component({
  // 你的组件元数据
})
export class YourComponent implements OnInit {
  ndate = new FormControl();

  ngOnInit(): void {
    // 格式化当前日期并赋值
    this.ndate.setValue(new Date().toISOString().slice(0, 16));
  }
}

关键说明

datetime-local控件仅接受YYYY-MM-DDTHH:mm格式的字符串值,new Date().toISOString()会生成包含毫秒的完整ISO字符串,通过slice(0, 16)截取后正好符合格式要求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.11 11:47:36