✅ 一、Date → 时间戳(毫秒)

✅ 核心方法:getTime()

java.util.Date 类提供了 getTime() 方法,直接返回自 UTC 纪元以来的毫秒数

✅ 操作步骤

  1. 创建或获取一个 Date 对象
  2. 调用其 getTime() 方法
  3. 得到 long 类型的时间戳

✅ 代码示例

import java.util.Date;

public class DateToTimestamp {
    public static void main(String[] args) {
        // 1. 创建一个 Date 对象(例如当前时间)
        Date date = new Date(); // 当前时间

        // 2. 转换为时间戳(毫秒)
        long timestamp = date.getTime();

        // 3. 输出结果
        System.out.println("Date: " + date);
        System.out.println("时间戳 (毫秒): " + timestamp);
        // 示例输出:1723667100123
    }
}

getTime() 返回的是 UTC 时间点的毫秒值,与时区无关。


✅ 二、时间戳 → Date

反过来,也可以用时间戳创建 Date 对象:

long timestamp = 1723667100123L;
Date date = new Date(timestamp);
System.out.println("对应的日期: " + date);

🔄 三、Date 与 Timestamp 的关系图

Date 对象
    ↓ getTime()
long 时间戳(毫秒) ←→ 自 1970-01-01 00:00:00 UTC 起的毫秒数
    ↑ new Date(long)
Date 对象

📌 关键理解Date 内部就是用一个 long 值(fastTime)存储时间戳的,getTime() 只是把这个值暴露出来。


⚠️ 常见误区

误区 正确认知
“时间戳有时区” ❌ 时间戳是绝对的,表示一个全球统一的时间点
“Date 有时区” Date 只是一个毫秒值,toString() 显示时才用默认时区格式化
System.currentTimeMillis()new Date().getTime() 不同 ❌ 两者本质相同,都返回当前时间的毫秒时间戳

✅ 四、实用技巧

1. 获取当前时间戳(推荐方式)

long nowTimestamp = System.currentTimeMillis();
// 或
long nowTimestamp2 = new Date().getTime();

System.currentTimeMillis() 略微高效,因为它不创建 Date 对象。

2. 计算时间差(例如:程序运行时间)

long start = System.currentTimeMillis();
// 执行某些操作...
long end = System.currentTimeMillis();

long duration = end - start; // 运行了多少毫秒
System.out.println("耗时: " + duration + " 毫秒");

3. 日期比较(基于时间戳)

Date date1 = new Date(1723667100000L);
Date date2 = new Date(1723667200000L);

long ts1 = date1.getTime();
long ts2 = date2.getTime();

if (ts1 < ts2) {
    System.out.println("date1 在 date2 之前");
}

✅ 五、Java 8+ 推荐:使用 Instant

虽然 Date.getTime() 依然有效,但在新项目中推荐使用 java.time 包:

import java.time.Instant;

// 获取当前时间戳(秒或毫秒)
long epochMilli = Instant.now().toEpochMilli(); // 毫秒
long epochSecond = Instant.now().getEpochSecond(); // 秒

// Instant ←→ Date 转换
Date date = Date.from(Instant.now());
Instant instant = date.toInstant();

✅ 优点:API 更清晰,类型更丰富,线程安全。


✅ 总结

操作 方法 代码
Date → 时间戳(毫秒) date.getTime() long ts = date.getTime();
时间戳 → Date new Date(timestamp) Date date = new Date(ts);
获取当前时间戳 System.currentTimeMillis() long now = System.currentTimeMillis();
推荐现代写法 Instant.now().toEpochMilli() long ts = Instant.now().toEpochMilli();

一句话记住
Date.getTime() 就是获取时间戳的 标准、简单、高效 方法。