You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Luxon .toLocaleString() 非美区域返回美式格式问题

问题解决:Luxon toLocaleString 区域格式化不生效

你的问题出在toLocaleString方法的参数传递错误。Luxon的toLocaleString有两种标准调用方式:

  1. 第一个参数是预定义格式(如DateTime.DATE_SHORT),第二个参数是包含locale的配置对象
  2. 第一个参数是Intl格式选项,第二个参数是包含locale的配置对象

你当前的写法把{ locale: 'en-gb' }作为第一个参数传入,Luxon会将其当作Intl的格式化选项而非区域配置,因此会默认使用美式格式。

正确代码示例

import { DateTime } from 'luxon';

// 使用预定义短日期格式 + 指定区域
console.log(DateTime.fromISO('2017-04-20').toLocaleString(DateTime.DATE_SHORT, { locale: 'en-gb' }));
// 输出:'20/04/2017'

// 或者自定义Intl格式选项 + 指定区域
console.log(DateTime.fromISO('2017-04-20').toLocaleString(
  { day: 'numeric', month: 'numeric', year: 'numeric' }, 
  { locale: 'en-gb' }
));
// 输出:'20/04/2017'

补充说明

  • 你测试原生Intl.DateTimeFormat正常,说明环境的区域支持没有问题,问题仅在于Luxon方法的参数使用错误
  • 如果需要使用其他区域格式,比如德语,同样按照这个写法:
    console.log(DateTime.fromISO('2018-08-13').toLocaleString(
      { day: 'numeric', month: 'long', year: 'numeric' }, 
      { locale: 'de' }
    ));
    // 输出:'13. August 2018'
    

内容的提问来源于stack exchange,提问作者Alex von Brandenfels

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 21:51:28