如何使用date-fns根据指定地区正确格式化时间为HH:mm
解决date-fns切换locale后时间格式输出不变的问题
你当前代码里使用的HH:mm是date-fns的固定格式令牌,这类令牌的显示规则不依赖地区(locale)——HH代表固定的24小时制小时(00-23),mm代表固定的两位分钟,所以无论切换哪个locale,输出结果自然一致。
要实现根据指定地区显示对应格式的时间,有两种常用方案:
方案一:使用本地化预设格式
date-fns内置了shortTime、mediumTime等预设格式名称,这些格式会自动适配你指定的locale:
import { format } from 'date-fns'; import { fr, enUS } from 'date-fns/locale'; const slot = '2022-10-19T18:30:00.000+02:00'; const targetDate = new Date(slot); // 法语地区(短时间格式为24小时制HH:mm) console.log(format(targetDate, 'shortTime', { locale: fr })); // 输出 "18:30" // 美国英语地区(短时间格式为12小时制带AM/PM) console.log(format(targetDate, 'shortTime', { locale: enUS })); // 输出 "6:30 PM"
方案二:动态获取locale的自定义格式
如果需要更精细的格式控制,可以直接获取对应locale的时间格式字符串,再传入format方法:
import { format } from 'date-fns'; import { fr, enUS } from 'date-fns/locale'; const slot = '2022-10-19T18:30:00.000+02:00'; const targetDate = new Date(slot); // 获取法语短时间格式字符串 const frTimeFormat = fr.formatLong.time({ width: 'short' }); console.log(format(targetDate, frTimeFormat, { locale: fr })); // 输出 "18:30" // 获取美国英语短时间格式字符串 const enTimeFormat = enUS.formatLong.time({ width: 'short' }); console.log(format(targetDate, enTimeFormat, { locale: enUS })); // 输出 "6:30 PM"
额外说明:区分地区格式与时区转换
如果你的需求是转换时区(比如把+02:00的时间转换成其他时区的时间),基础date-fns无法处理,需要使用date-fns-tz扩展包:
import { format } from 'date-fns-tz'; import { enUS } from 'date-fns/locale'; const slot = '2022-10-19T18:30:00.000+02:00'; const targetDate = new Date(slot); // 转换为纽约时区并按美国格式显示 console.log(format(targetDate, 'shortTime', { locale: enUS, timeZone: 'America/New_York' })); // 输出 "12:30 PM"
内容的提问来源于stack exchange,提问作者Aziz Triki
相关产品推荐
相关产品推荐

