Angular中time类型输入框时间显示偏差两小时问题求助
解决Angular mat-input time类型输入框时间偏差两小时的问题
问题根源在于使用[valueAsDate]绑定Date对象时,浏览器会基于本地时区解析Date对象的时分秒进行展示。若Date对象存储的是UTC时间,或本地时区与期望时间的时区存在偏移,就会出现显示偏差。
方案1:直接绑定字符串格式的时间(最简便)
跳过Date对象的时区解析,直接给input绑定HH:mm格式的字符串:
组件代码:
start_time: string = "07:45"; end_time: string = "12:00";
模板代码:
<mat-form-field> <mat-label>Start Time</mat-label> <input matInput type="time" [value]="start_time" #startInput> </mat-form-field> <mat-form-field> <mat-label>End Time</mat-label> <input matInput type="time" [value]="end_time" #endInput> </mat-form-field>
方案2:转换Date对象为目标时分秒字符串
如果必须使用Date对象,可根据需求转换为对应时区的时分秒字符串:
转换为本地时区时间
组件中添加方法:
getLocalTime(date: Date): string { const hours = date.getHours().toString().padStart(2, '0'); const minutes = date.getMinutes().toString().padStart(2, '0'); return `${hours}:${minutes}`; }
模板调用:
<input matInput type="time" [value]="getLocalTime(start_time)" #startInput>
转换为UTC时区时间
若期望展示UTC时间的时分秒:
getUTCTime(date: Date): string { const hours = date.getUTCHours().toString().padStart(2, '0'); const minutes = date.getUTCMinutes().toString().padStart(2, '0'); return `${hours}:${minutes}`; }
模板调用:
<input matInput type="time" [value]="getUTCTime(start_time)" #startInput>
方案3:调整Date对象匹配期望的显示时区
如果坚持使用[valueAsDate],需要让Date对象的对应时区时间与期望展示的时间一致:
- 若期望展示本地时区的7:45:
// 直接构造本地时间(注意月份为0基,6代表7月) start_time: Date = new Date(2023, 6, 14, 7, 45);
- 若期望展示UTC时区的7:45:
// 构造UTC时间的Date对象,需配合方案2的getUTCTime方法绑定,避免本地时区偏移 start_time: Date = new Date(Date.UTC(2023, 6, 14, 7, 45));
内容的提问来源于stack exchange,提问作者Lenntox
相关产品推荐
相关产品推荐

