You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何移除日期时区?解决date-fns月首尾日期的时区偏移问题

解决date-fns获取月份首尾日期的时区偏移问题

你的问题核心是本地时区与UTC时区的转换偏移:当前代码创建的是本地时区的日期,输出UTC格式时会自动转换,导致日期看起来提前了一天。以下是两种可靠的解决方法:

方法一:使用date-fns的UTC系列工具函数(推荐)

date-fns提供了专门的UTC版本函数,直接基于UTC时间计算,彻底避免时区转换问题:

const { addMonthsUTC, startOfMonthUTC, lastDayOfMonthUTC } = require('date-fns');

const today = new Date();
// 基于UTC时间计算下一个月
const monthPlusOne = addMonthsUTC(today, 1);

// 获取目标月份第一天的UTC时间
const firstDay = startOfMonthUTC(monthPlusOne);
// 获取目标月份最后一天的UTC时间
const lastDay = lastDayOfMonthUTC(firstDay);

// 输出标准UTC格式字符串
console.log(firstDay.toISOString()); // 2024-04-01T00:00:00.000Z
console.log(lastDay.toISOString()); // 2024-04-30T00:00:00.000Z

方法二:手动构造UTC日期对象

如果不想引入UTC系列函数,可以直接用Date.UTC()创建UTC时区的日期对象,确保时间戳对应UTC的00:00:

const { addMonths, lastDayOfMonth } = require('date-fns');

const today = new Date();
const monthPlusOne = addMonths(today, 1);

// 构造UTC时区的当月第一天
const firstDayUTC = new Date(Date.UTC(
  monthPlusOne.getUTCFullYear(),
  monthPlusOne.getUTCMonth(),
  1
));

// 构造UTC时区的当月最后一天
const lastDayLocal = lastDayOfMonth(monthPlusOne);
const lastDayUTC = new Date(Date.UTC(
  lastDayLocal.getUTCFullYear(),
  lastDayLocal.getUTCMonth(),
  lastDayLocal.getUTCDate()
));

console.log(firstDayUTC.toISOString());
console.log(lastDayUTC.toISOString());

问题原因说明

你原来的代码中new Date(year, month, 1)创建的是本地时区的00:00时刻,当通过console.log输出时,会自动转换为UTC时间格式。如果你的本地时区比UTC早2小时(比如UTC+2),本地的00:00就对应UTC的前一天22:00,导致日期显示为上月末或当月倒数第二天。

内容的提问来源于stack exchange,提问作者serverz

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.28 12:57:22