Components
DateTime
<DateTime> 组件 API 参考
概览
<DateTime> 组件用于渲染格式化的日期或时间字符串,支持自定义格式化 options 和 locale 等设置。
日期或时间将根据当前 locale 以及传入的可选参数进行格式化。
<DateTime>{1738010355}</DateTime>
// 输出:2025/1/27所有格式化均在本地由 Intl.DateTimeFormat 库完成。
参考资料
Props
Prop
Type
描述
| Prop 名称 | 描述 |
|---|---|
children | 组件内要渲染的内容。通常是日期或时间的值。如提供,将优先于 value 属性。 |
value | 日期或时间的默认值。可以是字符串、数字(时间戳)或 Date 对象。 |
options | 日期或时间的可选格式化选项,遵循 Intl.DateTimeFormatOptions 规范。可用于指定如星期名称、时区等格式。 |
locales | 可选的 locales,用于指定格式化所用的 locale。若未提供,则使用用户的 locale。关于指定 locales 的更多信息,请参阅此处。 |
返回值
包含格式化日期或时间字符串的 JSX.Element。
示例
基本用法
<DateTime> 组件用于显示本地化的日期或时间值。
import { DateTime } from 'gt-next';
export default function EventDate(event) {
return (
<DateTime>{event.date}</DateTime>
);
}指定 locales
<DateTime> 组件可用于在特定 locale 中显示日期或时间的 value。
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">
活动时间为<DateTime> {event.date} </DateTime>。 // [!code highlight]
</T>
);
}自定义格式
<DateTime> 组件支持自定义格式化 options。
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>等其他变量组件的更多详情和使用示例,
本指南如何?