如何根据不同语言区域(locale)格式化日期(如 2025-09-13 vs 09/13/2025)?
解读
国内项目普遍要同时服务国内(zh-CN)与海外(en-US、ja-JP 等)用户,日期格式是最直观也最容易踩坑的国际化需求。面试官问的不是“能不能”,而是“怎么做得优雅、可维护、可测试”,还要兼顾 NestJS 的依赖注入、配置中心、性能与缓存。回答时要体现:
- 国际化(i18n)与本地化(l10n)的区别
- 框架层(NestJS)与运行时(Node.js)如何协同
- 数据层、服务层、表现层各自的职责边界
- 异常兜底与缓存策略
知识点
- Intl.DateTimeFormat(ECMA-402)与 locale 优先级
- NestJS 官方生态 nestjs-i18n 的 I18nService、I18nContext、i18n 装饰器
- 自定义 Pipe/Interceptor 在序列化阶段统一格式化
- 配置中心(ConfigService)管理支持的 locale 白名单与回退规则
- 缓存:Intl 对象可复用,但格式器实例需按 locale + 选项缓存
- 测试:单元测试(service)、e2e(Accept-Language 头模拟)、快照测试(snapshot)
- 性能:高并发场景下避免每次 new Intl.DateTimeFormat,使用 LRU 或 WeakMap 缓存
- 安全:防止 locale 注入,必须校验 req.headers['accept-language'] 是否在白名单
答案
-
工程搭建
安装依赖npm i nestjs-i18n @nestjs/config在
app.module.ts中导入:I18nModule.forRoot({ fallbackLanguage: 'zh-CN', loader: I18nJsonLoader, loaderOptions: { path: path.join(__dirname, '/i18n/') }, resolvers: [ { use: QueryResolver, options: ['lang'] }, // ?lang=en-US AcceptLanguageResolver, // 请求头 new HeaderResolver(['x-lang']), // 自定义头 ], }) -
定义全局支持的日期格式
在src/config/i18n.config.ts:export const DATE_FORMAT = { 'zh-CN': { year: 'numeric', month: '2-digit', day: '2-digit' }, 'en-US': { year: 'numeric', month: '2-digit', day: '2-digit' }, } as const; export type SupportedLocale = keyof typeof DATE_FORMAT; -
封装 DateFormatter 服务
@Injectable() export class DateFormatter { private cache = new LRU<string, Intl.DateTimeFormat>(50); constructor(private config: ConfigService) {} format(date: Date, locale: SupportedLocale = 'zh-CN'): string { const key = `${locale}`; if (!this.cache.has(key)) { const opts = DATE_FORMAT[locale] ?? DATE_FORMAT['zh-CN']; this.cache.set(key, new Intl.DateTimeFormat(locale, opts)); } return this.cache.get(key)!.format(date); } } -
在业务 Service 中使用
@Injectable() export class OrderService { constructor( private formatter: DateFormatter, @I18n() private i18n: I18nContext, ) {} async getOrder(id: string) { const order = await this.orderRepo.findOne(id); return { ...order, createTimeFormatted: this.formatter.format( order.createTime, this.i18n.lang as SupportedLocale, ), }; } } -
统一在拦截器里做序列化(可选)
如果返回 DTO 字段很多,可写@Transform配合class-transformer,或自定义FormatDateInterceptor,把带@FormatDate()装饰器的字段自动格式化,避免业务代码重复调用。 -
异常与回退
若请求传入非法 locale(如xx-YY),I18nModule会回退到fallbackLanguage,DateFormatter也同步回退到zh-CN,保证接口永远返回可读日期。 -
单元测试示例
it('应返回 2025-09-13 格式', () => { const fmt = new DateFormatter(config); expect(fmt.format(new Date('2025-09-13'), 'zh-CN')).toBe('2025-09-13'); });
拓展思考
- 时区问题:Intl.DateTimeFormat 默认使用运行系统时区,生产容器通常设为 UTC。若用户需要“本地时间”,需把
timeZone参数也加入缓存 key,来源可以是用户资料字段user.timezone,或前端在 Header 带X-Timezone: Asia/Shanghai。 - 多格式并存:除了短日期,可能还需要“YYYY年MM月DD日”、“MMM dd, yyyy”等,可把
DATE_FORMAT升级为二维 Map,支持short | long | monthOnly等风格,通过@FormatDate('long')注解指定。 - 与数据库交互:
- 存储统一用 UTC 时间戳或 timestamptz,绝不存格式化字符串
- 查询时若按“日期”过滤,需把用户输入的本地字符串先解析成 Date,使用
date-fns-tz或luxon做时区转换,再生成 SQL 条件
- 性能极限优化:
- 高并发接口可预生成静态格式器,在
onModuleInit阶段把白名单 locale 全部 new 出来放入只读 Map,彻底消灭运行时 new - 若部署在 Serverless(阿里云 FC、腾讯云 SCF),冷启动时要控制 I18n 语言包体积,可用
nestjs-i18n的includeFallbacks: false并只打包用到的语言
- 高并发接口可预生成静态格式器,在
- 与 GraphQL 集成:
- 在
FieldResolver里注入I18nContext,对createdAt字段统一格式化,避免每个 resolver 手写
- 在
- 合规:国内金融、政务项目要求 GB/T 7408-2005 格式(即
yyyy-MM-dd),即便用户 locale 是 en-US,也必须在特定接口强制覆盖,可通过@ForceLocale()自定义装饰器实现白名单接口级别的格式锁定