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

Angular Material time类型输入框如何设置为24小时格式

如何将Angular Material的Time输入框配置为24小时格式?

嘿,我来帮你搞定这个问题!Angular Material的type="time"输入框默认会根据当前的区域设置(locale)来决定显示12小时制还是24小时制,所以我们只需要调整区域配置就能轻松切换到24小时格式,具体有两种常用方法:

方法一:全局配置区域设置

这种方法会让整个应用的时间/日期组件都使用24小时制,适合大多数场景:

  1. 打开你的根模块文件(通常是app.module.ts),导入LOCALE_ID并在providers中配置支持24小时制的区域代码,比如zh-CN(中文)、en-GB(英式英语)、de-DE(德语)等:
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { LOCALE_ID } from '@angular/core';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { MatInputModule } from '@angular/material/input';

import { AppComponent } from './app.component';

@NgModule({
  declarations: [AppComponent],
  imports: [BrowserModule, BrowserAnimationsModule, MatInputModule],
  providers: [
    { provide: LOCALE_ID, useValue: 'zh-CN' } // 替换为你需要的24小时制区域
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }
  1. 保持你原有的模板代码不变,输入框会自动适配成24小时格式:
<md-input-container class="input-material-element">
  <input mdInput type="time" placeholder="{{labels.TIME_OF_DEPARTURE}}" [(ngModel)]="model.departureTime">
</md-input-container>

方法二:单个组件单独配置

如果你只想让某个特定组件的时间输入框使用24小时制,不想影响全局,可以在组件内部单独配置:

在你的组件类文件中,在@Component装饰器的providers数组里添加区域配置:

import { Component, LOCALE_ID } from '@angular/core';

@Component({
  selector: 'app-your-time-component',
  templateUrl: './your-time-component.component.html',
  providers: [{ provide: LOCALE_ID, useValue: 'en-GB' }] // 这里设置目标区域
})
export class YourTimeComponent {
  labels = { TIME_OF_DEPARTURE: '出发时间' }; // 示例标签
  model = { departureTime: '' };
}

额外注意事项

  • 确保你绑定的model.departureTime是24小时制的时间字符串(比如'08:30'、'19:15'),这样双向绑定才能正常工作。
  • 不同的区域代码可能会有细微的格式差异,但只要是默认使用24小时制的区域,都能满足你的需求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 07:47:10