jsAPI:Intl.DateTimeFormat 属性含义
Intl.DateTimeFormat用于格式化日期和时间。它可以根据不同地区的语言和文化习惯来格式化日期和时间,并且支持多种格式。下面是一个使用Intl.DateTimeFormat的示例代码:
const date = new Date();
const options = { year: 'numeric', month: 'long', day: 'numeric' };
const formatter = new Intl.DateTimeFormat('zh-CN', options);
console.log(formatter.format(date)); // 输出:2025年5月26日
在上面的代码中,我们首先创建了一个Date对象,然后定义了一个options对象,该对象指定了要格式化的日期的具体格式。接着,我们创建了一个Intl.DateTimeFormat对象,并将其传递给指定语言环境('zh-CN'表示中文环境)。最后,我们调用formatter.format()方法来格式化日期,并输出结果。
需要注意的是,在创建Intl.DateTimeFormat对象时,我们可以传递一个options对象来指定日期的格式。这个options对象可以包含以下属性:
localeMatcher:指定语言环境匹配方式("lookup"或"best fit")。
"lookup":使用 Lookup 匹配算法,严格按照用户提供的语言环境列表进行匹配,依次查找最接近的支持的语言环境,不进行智能推测。"best fit":使用 Best Fit 匹配算法(默认),根据用户的语言环境请求和系统支持的语言环境,智能选择最合适的结果,可能会返回一个更合适的替代语言环境。
weekday:指定星期几的格式("narrow"、"short"或"long")。
"narrow":星期几以最简短的形式显示,通常为一个字符(例如:S, M, T, W, T, F, S)。"short":星期几以简写形式显示(例如:Sun, Mon, Tue, Wed, Thu, Fri, Sat)。"long":星期几以完整名称形式显示(例如:Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday)。
era:指定年代的格式("narrow"、"short"或"long")。
"narrow":年代以最简短的形式表示(例如:B(公元前)、A(公元))。"short":年代以简写形式表示(例如:BC(公元前)、AD(公元))。"long":年代以完整名称表示(例如:Before Christ(公元前)、Anno Domini(公元))。
year:指定年份的格式("numeric"、"2-digit")。
"numeric":年份以完整的数字形式显示(例如:2025, 2026)。"2-digit":年份以两位数的形式显示,不足两位前面补零(例如:25, 26)。
month:指定月份的格式("numeric"、"2-digit"、"narrow"、"short"或"long")。
"numeric":月份以数字形式显示(例如:1, 2, ..., 12)。"2-digit":月份以两位数的字符串形式显示,不足两位前面补零(例如:01, 02, ..., 12)。"narrow":月份以最简短的形式显示,通常为一个字符(例如:J, F, M, ...)。"short":月份以标准的缩写字符串形式显示(例如:Jan, Feb, Mar, ...)。"long":月份以完整的名称形式显示(例如:January, February, March, ...)。
day:指定日期的格式("numeric"、"2-digit")。
hour:指定小时的格式("numeric"、"2-digit")。
minute:指定分钟的格式("numeric"、"2-digit")。
second:指定秒钟的格式("numeric"、"2-digit")。
timeZoneName:指定时区名称的格式("short"或"long")。
"short":以简写形式显示时区名称(例如:PST, CST, UTC)。"long":以完整名称形式显示时区(例如:Pacific Standard Time, Central European Time)。
