Components

DateTime

<DateTime> 组件 API 参考

概览

<DateTime> 组件用于渲染格式化后的日期或时间字符串,支持通过格式化 options 和 locale 等进行自定义。 日期或时间将根据当前 locale 以及传入的可选参数进行格式化。

<DateTime>{1738010355}</DateTime>
// 输出:1/27/2025

所有格式化均由本地使用 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-react';

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

指定 locales

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

EventDate.jsx

import { DateTime } from 'gt-react';

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

翻译 <DateTime>

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

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

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

自定义格式

<DateTime> 组件支持自定义 options 来设置格式。

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

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