Components
<DateTime>
<DateTime> 组件的 API 参考
概述
<DateTime>
组件渲染格式化的日期或时间字符串,支持自定义格式选项和区域设置等。
日期或时间根据当前区域设置和传递的任何可选参数进行格式化。
<DateTime>{1738010355}</DateTime>
// Output: 1/27/2025
所有格式化都使用 Intl.DateTimeFormat
库在本地处理。
参考
Props
Prop | Type | Default |
---|---|---|
locales?? | string[] | undefined |
options?? | Intl.DateTimeFormatOptions | {} |
value?? | string | number | Date | undefined |
name?? | string | undefined |
children?? | any | undefined |
描述
属性名称 | 描述 |
---|---|
children | 在组件内部渲染的内容。通常是日期或时间值。如果提供,它将优先于 value 属性。 |
value | 日期或时间的默认值。可以是字符串、数字(时间戳)或 Date 对象。 |
options | 日期或时间的可选格式化选项,遵循 Intl.DateTimeFormatOptions 规范。使用此选项定义样式,如星期几名称、时区等。 |
locales | 可选的区域设置,用于指定格式化区域。如果未提供,将使用用户的区域设置。在此处了解更多关于指定区域设置的信息。 |
返回值
包含格式化日期或时间字符串的 JSX.Element
。
示例
基本用法
<DateTime>
组件可用于显示本地化的日期或时间值。
import { DateTime } from 'gt-next';
export default function EventDate(event) {
return (
<DateTime> {event.date} </DateTime>.
);
}
指定区域设置
<DateTime>
组件可用于显示特定区域设置的日期或时间值。
import { DateTime } from 'gt-next';
export default function EventDate(event) {
return (
<DateTime locales={['fr-FR']}> {event.date} </DateTime>.
);
}
翻译 <DateTime>
假设您希望日期时间显示在一个同样被翻译的句子中。
您可以将 <DateTime>
组件包装在 <T>
组件中。
import { T, DateTime } from 'gt-next';
export default function EventDate(event) {
return (
<T id="eventDate">
The time of the event is <DateTime> {event.date} </DateTime>. // [!code highlight]
</T>
);
}
自定义格式化
<DateTime>
组件支持自定义格式化选项。
import { DateTime } from 'gt-next';
export default function EventDate(event) {
return (
<DateTime options={{
dateStyle: 'full',
timeStyle: 'long',
timeZone: 'Australia/Sydney',
}}>
{event.date}
</DateTime>.
);
}
注意事项
<DateTime>
组件是一个可变组件,可用于格式化日期和时间值。- 该组件使用
Intl.DateTimeFormat
库进行格式化。
后续步骤
- 有关
<DateTime>
组件以及其他变量组件如<Currency>
、<Num>
和<Var>
的更多详细信息和使用示例, 请参阅 使用变量组件 文档。
这份指南怎么样?