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

如何获取指定年份中每个月的起止时间戳

实现方法整理

通用逻辑

不需要基于已拿到的年首尾时间戳做拆分,直接基于目标年份生成每个月的起止时间戳准确率更高,可避免时区差异、闰秒等问题导致的误差,核心逻辑如下:

  • 遍历1-12月,分别生成当月1日00:00:00的时间戳作为月起始值
  • 生成下一个月1日00:00:00的时间戳,减1毫秒即为当月最后一秒的时间戳作为月结束值
  • 可直接把1月起始值替换为你已有的yearStart、12月结束值替换为yearEnd,完全对齐你给定的年时间范围

代码实现示例

JavaScript 示例

function getMonthTimestamps(targetYear, yearStart, yearEnd) {
  const monthTimestampList = []
  // JS月份从0开始计数,所以遍历0-11对应1-12月
  for (let monthIdx = 0; monthIdx < 12; monthIdx++) {
    const monthStart = monthIdx === 0 ? yearStart : new Date(targetYear, monthIdx, 1).getTime()
    const monthEnd = monthIdx === 11 ? yearEnd : new Date(targetYear, monthIdx + 1, 1).getTime() - 1
    monthTimestampList.push({
      month: monthIdx + 1,
      startTimestamp: monthStart,
      endTimestamp: monthEnd
    })
  }
  return monthTimestampList
}

// 2021年调用示例
const result = getMonthTimestamps(2021, 1609455600000, 1640991599000)

Python 示例

import datetime
import time

def get_month_timestamps(target_year, year_start, year_end):
    month_timestamp_list = []
    for month in range(1, 13):
        # 计算当月起始时间戳
        if month == 1:
            month_start = year_start
        else:
            month_start = int(time.mktime(datetime.date(target_year, month, 1).timetuple()) * 1000)
        # 计算当月结束时间戳
        if month == 12:
            month_end = year_end
        else:
            next_month_start = int(time.mktime(datetime.date(target_year, month + 1, 1).timetuple()) * 1000)
            month_end = next_month_start - 1
        month_timestamp_list.append({
            "month": month,
            "startTimestamp": month_start,
            "endTimestamp": month_end
        })
    return month_timestamp_list

# 2021年调用示例
result = get_month_timestamps(2021, 1609455600000, 1640991599000)

注意事项

  • 如果业务涉及跨时区需求,需要将生成时间的时区对齐到业务使用的标准时区,避免生成的时间戳出现小时级偏差
  • 用下月首日减1毫秒的方式不需要手动判断当月是28/30/31天,可自动适配闰年2月的特殊情况

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 15:09:04