如何使用date-fns-tz获取指定时区午夜对应的UTC时间
使用date-fns-tz实现指定时区的午夜UTC时间获取方案
完整实现代码
确保已安装date-fns和date-fns-tz依赖后,可按以下方式实现目标函数:
import { formatInTimeZone, parseInTimeZone } from 'date-fns-tz'; export function getInstantAtMidnightForTimezoneForGivenInstant(instant: number | Date, tz: string): Date { // 生成目标时区当天午夜的时间字符串 const midnightAtTimezoneString = formatInTimeZone(instant, tz, 'yyyy-MM-dd 00:00:00'); // 按目标时区解析字符串,得到对应UTC时间的Date对象 return parseInTimeZone(midnightAtTimezoneString, tz, 'yyyy-MM-dd HH:mm:ss'); }
代码说明
formatInTimeZone:将输入的时间戳/Date对象转换为目标时区的日期字符串,固定为当天的00:00:00(午夜时分)。parseInTimeZone:将生成的午夜字符串按照指定时区解析为Date对象。由于Date对象本质存储的是UTC时间戳,因此返回的结果正好是对应时区午夜的UTC时间,完全匹配测试用例的预期。
验证用例(Jest)
import { parseISO } from 'date-fns'; import { getInstantAtMidnightForTimezoneForGivenInstant } from './你的文件路径'; it('应该符合预期逻辑', () => { // 输入时间戳对应UTC时间:2022-08-23T22:29:21Z expect( getInstantAtMidnightForTimezoneForGivenInstant(1661357361000, 'America/Toronto') ).toEqual(parseISO('2022-08-24T04:00:00Z')); // 多伦多午夜转为UTC是次日04:00 expect( getInstantAtMidnightForTimezoneForGivenInstant(1661357361000, 'Asia/Kolkata') ).toEqual(parseISO('2022-08-23T18:30:00Z')); // 加尔各答午夜转为UTC是当天18:30 });
内容的提问来源于stack exchange,提问作者Archimedes Trajano
相关产品推荐
相关产品推荐

