如何使用date-fns复刻基于moment.js实现的本地时间转换函数
Convert UTC Hour to Local Hour with date-fns (Replacing moment.js Function)
First, let's break down what your original moment.js function is actually doing:
- It creates a moment object tied to the current date, setting the local hour to
userHour - It fetches your current timezone's offset from UTC (in minutes) using
utcOffset() - It converts that offset to hours and adds it to
userHour—this effectively turns a UTC hour into its matching local time hour (for example, UTC 4 AM becomes 12 PM in UTC+8 timezones)
To replicate this logic with date-fns, we can use native JavaScript Date functionality (which date-fns works seamlessly with) since date-fns doesn't have a direct drop-in for moment's utcOffset(), but the end result is easy to achieve:
// If you prefer using date-fns's helper instead of native Date, import this // import { getTimezoneOffset } from 'date-fns'; const convertToLocalTime = (userHour) => { // Get timezone offset in minutes (use native Date or date-fns's method) const offsetMinutes = new Date().getTimezoneOffset(); // OR use date-fns: // const offsetMinutes = getTimezoneOffset(new Date()); // Adjust the offset to match moment's logic: native offset is UTC minus local time, so invert it const offsetHours = -offsetMinutes / 60; // Apply the same calculation as your original function return userHour + offsetHours; }; console.log(convertToLocalTime(4));
Important Details:
- Native
Date.getTimezoneOffset()returns how many minutes UTC is ahead of your local time (so for UTC+8, it returns -480). Inverting this gives us the local offset relative to UTC (8 hours), which matches exactly whatmoment().utcOffset() / 60returns. - Just like your original moment function, this uses the current date's timezone offset—so it automatically accounts for daylight saving time if your timezone observes it.
- Using date-fns's
getTimezoneOffsetis optional; it's just a wrapper around the native method to keep your code aligned with date-fns's API style.
内容的提问来源于stack exchange,提问作者Asking
相关产品推荐
相关产品推荐

