React Big Calendar时间偏移问题:日期格式转换方案
React项目中react-big-calendar时间偏移1小时问题解决
在React项目使用react-big-calendar组件时,遇到了时间显示偏移1小时的问题,推测是夏令时与时区差异导致的。从Microsoft Graph获取的Event对象中,开始和结束日期的格式为"2022-11-16T07:30:00.0000000",需要转换为符合ISO 8601标准的"2022-11-16T07:30:00.0z"格式,但原代码无法正确解析这些日期属性。
原代码如下:
const data = calendarEvent.map((event: microsoftgraph.Event) => { return { id: event.id, title: event.location.displayName, allDay: false, start: new Date(event.start.dateTime), end: new Date(event.end.dateTime), } });
解决方案
在event.start.dateTime和event.end.dateTime后拼接字符串"z",让JavaScript的Date对象将其识别为UTC时间,从而避免本地时区转换带来的时间偏移问题。修改后的代码如下:
const data = calendarEvent.map((event: microsoftgraph.Event) => { return { id: event.id, title: event.location.displayName, allDay: false, start: new Date(event.start.dateTime + "z"), end: new Date(event.end.dateTime + "z"), } });
内容的提问来源于stack exchange,提问作者liondepierre
相关产品推荐
相关产品推荐

