1. 方法定义

public long getTime()
  • 所属类java.util.Date
  • 返回值long 类型,表示自 1970年1月1日 00:00:00 GMT(Unix纪元) 以来的毫秒数。
  • 功能:获取当前 Date 对象对应的时间戳(毫秒值)。

2. 功能说明

  • 返回当前 Date 对象与 Unix纪元 的时间差(毫秒)。
  • 时间戳可跨时区、跨平台使用,适合时间计算和存储。
  • 示例:1672531200000 表示 2023-01-01 00:00:00 GMT。

3. 示例代码

import java.util.Date;

public class DateExample {
    public static void main(String[] args) {
        // 创建当前时间的Date对象
        Date now = new Date();
        
        // 获取时间戳(毫秒)
        long timestamp = now.getTime();
        System.out.println("当前时间戳: " + timestamp);
        
        // 时间戳转换为Date对象
        Date dateFromTimestamp = new Date(timestamp);
        System.out.println("转换后的Date: " + dateFromTimestamp);
        
        // 计算时间差(例如:24小时后)
        long oneDayInMillis = 24 * 60 * 60 * 1000;
        Date tomorrow = new Date(timestamp + oneDayInMillis);
        System.out.println("24小时后的时间: " + tomorrow);
    }
}

4. 使用技巧

  1. 时间比较
    直接比较时间戳而非 Date 对象:

    boolean isAfter = date1.getTime() > date2.getTime();
    
  2. 时间计算
    通过毫秒数加减实现时间偏移:

    // 30分钟后
    long thirtyMinutesLater = new Date().getTime() + 30 * 60 * 1000;
    
  3. 存储与传输
    在数据库或网络传输中存储时间戳(long),而非 Date 对象。


5. 常见错误

  1. 时区混淆
    getTime() 返回 GMT 时间戳,但 Date.toString() 显示本地时区时间。
    错误示例

    Date date = new Date(0); // 1970-01-01 GMT
    System.out.println(date); // 输出可能为1969-12-31(本地时区)
    
  2. 精度问题
    时间戳单位为毫秒,若需秒级精度需手动转换:

    long seconds = date.getTime() / 1000; // 秒级时间戳
    
  3. 忽略日期可变性
    Date 对象是可变的,直接修改可能导致意外结果:

    Date date = new Date();
    long timestamp = date.getTime();
    date.setTime(timestamp + 1000); // 修改原始对象!
    

6. 注意事项

  1. 时区敏感

    • getTime() 始终基于 GMT
    • 显示时间时需明确时区(推荐使用 SimpleDateFormatjava.time.ZoneId)。
  2. 纪元范围

    • 有效时间:约 290,000,000 年(Long.MIN_VALUELong.MAX_VALUE)。
    • 1970年之前的时间戳为负数。
  3. 替代方案
    Java 8+ 推荐使用 java.time.Instant

    Instant.now().toEpochMilli(); // 等效于 new Date().getTime()
    

7. 最佳实践与性能优化

  1. 优先使用 java.time

    // Java 8+ 推荐方式
    long timestamp = Instant.now().toEpochMilli();
    
    • 原因:java.time 线程安全、API 丰富(如 DurationZonedDateTime)。
  2. 避免频繁创建 Date 对象

    // 需要时间戳时直接使用System.currentTimeMillis()
    long timestamp = System.currentTimeMillis(); // 比 new Date().getTime() 高效
    
  3. 同步问题
    多线程环境避免共享可变 Date 对象,改用不可变类型(如 Instant)。

  4. 日期格式化
    使用 SimpleDateFormat 时注意线程安全(推荐 ThreadLocalDateTimeFormatter)。