typescript - 时间日期选项作为单独的变量
问题描述
我目前有点头疼,试图用 Typescript /React 格式化显示在 Web 组件上的时间
下面的代码工作正常:
new Date(myDate)
.toLocaleTimeString(
'en-US',
{ weekday: 'short', year: 'numeric', month: 'short', day: 'numeric', hour12: false });
但是我正在尝试在多个位置重用该格式选项,所以我正在尝试这个并且它不起作用:
const timeformat = { weekday: 'short', year: 'numeric', month: 'short', day: 'numeric', hour12: false };
new Date(status.start).toLocaleTimeString('en-US',timeformat);
TypeScript 会抛出这样的错误:
Argument of type '{ weekday: string; year: string; month: string; day: string; hour12: boolean; }' is not assignable to parameter of type 'DateTimeFormatOptions'.
Types of property 'weekday' are incompatible.
Type 'string' is not assignable to type '"short" | "long" | "narrow" | undefined'. TS2345
我努力了
const timeFormat : DateTimeFormatOptions = {...}
但它找不到类型。
请帮忙!!
太感谢了!!
解决方案
这应该可以解决您的问题:
let timeformat = new Intl.DateTimeFormatOptions('en-US', { weekday: 'short', year: 'numeric', month: 'short', day: 'numeric', hour12: false });