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

如何计算下一小时开始时刻的毫秒级Epoch时间戳?

计算下一小时整点的毫秒级Epoch时间戳

核心思路是先构造出下一小时的整点时刻,再转换为毫秒级时间戳,而非直接给当前时间累加一小时(避免跨天、夏令时切换等场景下的误差)。以下是几种主流编程语言的实现示例:

JavaScript

// 获取当前时间
const now = new Date();
// 构造下一小时整点:年、月、日不变,小时+1,分/秒/毫秒置0
const nextHourStart = new Date(now.getFullYear(), now.getMonth(), now.getDate(), now.getHours() + 1, 0, 0, 0);
// 转换为毫秒级Epoch时间戳
const nextHourTimestamp = nextHourStart.getTime();

// 存储为属性示例
const timeHolder = {
  nextHourEpochMs: nextHourTimestamp
};

Python

import datetime

now = datetime.datetime.now()
// 替换当前时间的小时为"当前小时+1",同时置零分/秒/微秒
next_hour_start = now.replace(hour=now.hour + 1, minute=0, second=0, microsecond=0)
// 转换为毫秒级时间戳(timestamp()返回秒级,乘1000转为毫秒)
next_hour_timestamp = int(next_hour_start.timestamp() * 1000)

// 存储为类属性示例
class TimeStore:
    def __init__(self):
        self.next_hour_epoch_ms = next_hour_timestamp

store = TimeStore()

Java(Java 8+)

import java.time.LocalDateTime;
import java.time.ZoneOffset;

public class HourTimestamp {
    // 存储为类属性
    private long nextHourEpochMs;

    public HourTimestamp() {
        LocalDateTime now = LocalDateTime.now();
        // 先加1小时,再置零分/秒/纳秒,确保是整点
        LocalDateTime nextHourStart = now.plusHours(1).withMinute(0).withSecond(0).withNano(0);
        // 转换为毫秒级Epoch时间戳(可指定时区,这里用系统默认时区)
        this.nextHourEpochMs = nextHourStart.toInstant(ZoneOffset.systemDefault()).toEpochMilli();
    }

    public static void main(String[] args) {
        HourTimestamp ts = new HourTimestamp();
        System.out.println(ts.nextHourEpochMs);
    }
}

关键注意点

直接累加3600000毫秒(1小时)的方式不可靠:比如遇到夏令时切换时,一天可能不是24小时,或者当前时间是23:30,累加1小时会得到次日00:30,而非期望的次日00:00。通过构造整点时刻的方式能避免这些问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.09 05:27:12