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日期或时间的可选格式化选项,遵循 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 中显示日期或时间的 value。

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> 组件是一个变量组件,可用于格式化日期和时间的 value。
  • 该组件使用 Intl.DateTimeFormat 库进行格式化。

后续步骤

  • 如需了解 <DateTime> 组件及其他变量组件(如 <Currency><Num><Var>)的更多详情与使用示例,

本指南如何?