PKU harness

format

按界面语言格式化日期和时间的函数,以及用来定义多语言字符串表的 defineStrings。

这个模块帮你按 App 当前的语言显示文字。它提供两类工具:一是定义插件的中英文字符串表,二是把日期、时间和倒计时格式化成符合该语言习惯的字符串。

源码:packages/sdk/src/format.ts。指南:多语言。下文中的 locale 参数类型是 AppLocale,取值为 'zh-Hans' | 'en'。

App 运行在 React Native 的 JavaScript 引擎 Hermes 上。Hermes 的 Intl 会忽略 locale 参数,所以这些函数不使用 Intl,自己拼出字符串。它们的输出和 App 自身的日期格式一致,插件界面因此和 App 其他地方保持统一。这些函数都是纯函数,测试时传入 now 参数即可得到固定结果。

字符串表

字符串表把同一组文案的中文版和英文版放在一起。defineStrings 以中文版为准做类型检查:英文版少了或多了某个键,或者值的类型不同,编译时就会报错。

/** 按语言划分的字符串表;`en` 的键(以及值的类型)必须与 `zh-Hans` 完全一致。 */
type Localized<T> = { 'zh-Hans': T; en: T };

/** 定义插件的字符串表,`en` 按 `zh-Hans` 做类型检查。 */
const defineStrings: <T>(table: { 'zh-Hans': T; en: NoInfer<T> }) => Localized<T>;

日期和时间

下表列出各个格式化函数的签名,以及它们在两种语言下的输出示例。

函数签名zh-Hansen
formatClock(d: Date | number, seconds?: boolean) => string21:04 / 21:04:37同左
formatWeekday(d: Date | number, locale) => string周一Mon
weekdayName(weekday: number, locale) => string(1 = 周一 … 7 = 周日,0 也表示周日)周一Mon
formatLocalDate(d, locale, now?) => string(不是今年时带上年份)10月18日、2025年10月18日Oct 18、Oct 18, 2025
formatLocalDateTime(d, locale, now?) => string10月18日 21:04Oct 18, 21:04
formatRelative(ms: number, locale, now?) => string(过去的时间戳)刚刚、3 分钟前、21:04、昨天 21:04,再往前是日期加时间Just now、3 min ago、21:04、Yesterday 21:04 ……
formatDay(d, locale, now?) => string今天、明天、昨天、周三(未来一周内)、日期Today、Tomorrow、Yesterday、Wed、日期
formatCountdown(ms: number, locale) => string(剩余时间)3天5小时、2小时10分、8分钟、不到1分钟、已到3d 5h、2h 10m、8 min、<1 min、Now
dayDiff(d, now?) => number距今天的自然日数(0 今天,1 明天,−1 昨天),不受夏令时影响
plural(n: number, one: string, many?: string) => string—plural(3, 'book') → 3 books
import { formatCountdown, formatRelative } from '@pku-harness/sdk';

const locale = host.useLocale();
formatRelative(data.updatedAt ?? Date.now(), locale);      // "3 分钟前" / "3 min ago"
formatCountdown(deadline - Date.now(), locale);            // "2小时10分" / "2h 10m"

这些函数用于给用户看的界面。给模型看的时间戳另有处理:宿主会在每一轮对话中附上当前时间,定时相关的工具则使用 scheduler 里的 formatLocal,输出形如 "2026-10-20 08:00 周二"。

本页目录