Titanium SDK 中的 Intl.DateTimeFormat 国际化日期时间格式化指南
概述
在 Titanium SDK 中,Global.Intl.DateTimeFormat 是一个不可变对象,用于生成本地化的日期和时间格式化字符串。它能够根据系统当前的语言设置输出完整的月份或星期名称,并遵循当前地区的日期组件顺序(如月/日/年、日/月/年或年/月/日)。
基本用法
创建 DateTimeFormat 实例
要使用 DateTimeFormat,首先需要创建一个实例:
const formatter = new Intl.DateTimeFormat(locales, options);
locales:可选参数,指定语言和国家代码(BCP 47格式),可以是字符串或字符串数组options:可选参数,提供格式化选项对象
建议使用当前系统地区设置:
const formatter = new Intl.DateTimeFormat(Ti.Locale.currentLocale, options);
格式化日期
创建实例后,可以使用 format() 方法格式化日期:
const formattedDate = formatter.format(new Date());
常用格式化选项
DateTimeFormat 提供了丰富的格式化选项,下面介绍一些常用选项:
日期格式化
-
year:年份格式
'numeric':4位数字(如 2020)'2-digit':2位数字(如 20)
-
month:月份格式
'numeric':数字(如 3)'2-digit':2位数字(如 03)'short':缩写(如 Mar)'long':全称(如 March)
-
day:日期格式
'numeric':数字(如 1)'2-digit':2位数字(如 01)
时间格式化
-
hour:小时格式
'numeric':数字(如 1)'2-digit':2位数字(如 01)
-
minute/second:分钟/秒格式
- 选项与小时相同
-
hour12:是否使用12小时制
true:12小时制(显示AM/PM)false:24小时制
其他选项
-
timeZone:时区设置
- 如
'UTC'或'Asia/Shanghai'
- 如
-
weekday:星期格式
'short':缩写(如 Mon)'long':全称(如 Monday)
实用示例
示例1:格式化数字日期
const date = new Date(Date.UTC(2020, 2, 1));
const formatter = new Intl.DateTimeFormat(Ti.Locale.currentLocale, {
year: 'numeric',
month: 'numeric',
day: 'numeric',
timeZone: 'UTC'
});
console.log(formatter.format(date));
不同地区输出:
- 美国英语:"3/1/2020"
- 德语:"1.3.2020"
- 日语:"2020/3/1"
示例2:12小时制时间
const date = new Date(Date.UTC(2020, 0, 1, 20, 2, 5));
const formatter = new Intl.DateTimeFormat(Ti.Locale.currentLocale, {
hour: 'numeric',
minute: '2-digit',
second: '2-digit',
hour12: true,
dayPeriod: 'narrow',
timeZone: 'UTC'
});
console.log(formatter.format(date));
不同语言输出:
- 英语:"8:02:05 PM"
- 德语:"8:02:05 nachm."
示例3:24小时制时间
const formatter = new Intl.DateTimeFormat(Ti.Locale.currentLocale, {
hour: '2-digit',
minute: '2-digit',
second: '2-digit',
hour12: false,
timeZone: 'UTC'
});
console.log(formatter.format(date));
输出:"20:02:05"
高级功能
formatToParts 方法
formatToParts() 方法可以将格式化结果分解为各个组成部分:
const parts = formatter.formatToParts(new Date());
返回的数组包含对象,每个对象有 type 和 value 属性,可用于分析日期格式的各个部分。
resolvedOptions 方法
获取格式化对象使用的选项:
const options = formatter.resolvedOptions();
supportedLocalesOf 方法(静态)
检查哪些地区被支持:
const supportedLocales = Intl.DateTimeFormat.supportedLocalesOf(['zh-CN', 'en-US']);
平台注意事项
-
Android特有选项:
dateStyle和timeStyle仅在Android上支持fractionalSecondDigits可显示毫秒(0-3位)
-
iOS/MacOS特有选项:
localeMatcher和formatMatcher仅在iOS/MacOS上有效
最佳实践
- 总是使用
Ti.Locale.currentLocale获取当前地区设置 - 对于需要特定格式的场景,明确指定所有相关选项
- 使用
formatToParts()分析地区特定的日期组件顺序 - 考虑用户偏好设置(如12/24小时制)
通过合理使用 Intl.DateTimeFormat,开发者可以轻松实现应用程序的日期时间本地化,提供更好的用户体验。
创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考



