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日期或时间的可选格式化 options,遵循 Intl.DateTimeFormatOptions 规范。可用于设置如星期名称、时区等格式。
locales可选的 locales,用于指定格式化所用的 locale。若未提供,则使用用户的 locale。有关指定 locales 的更多信息请参见此处

返回值

一个 JSX.Element,其中包含格式化后的日期或时间字符串。


示例

基本用法

<DateTime> 组件用于显示本地化的日期或时间。

EventDate.jsx
import { DateTime } from 'gt-next';

export default function EventDate(event) {
    return (
        <DateTime> {event.date} </DateTime>。 
    );
}

指定 locales

<DateTime> 组件可用于按特定 locale 显示日期或时间值。

EventDate.jsx

import { DateTime } from 'gt-next';

export default function EventDate(event) {
    return (
        <DateTime locales={['fr-FR']}> {event.date} </DateTime>. 
    );
}

翻译 <DateTime>

假设你希望在一段同样会被翻译的句子中显示日期时间。 你可以将 <DateTime> 组件包裹在 <T> 组件中。

EventDate.jsx
import { T, DateTime } from 'gt-next';

export default function EventDate(event) {
    return (
        <T id="eventDate">
            活动时间为<DateTime>{event.date}</DateTime>。 // [!code highlight]
        </T>
    );
}

自定义格式

<DateTime> 组件支持自定义格式化 options。

EventDate.jsx
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>)的更多详情与使用示例,

这份指南怎么样?

DateTime