杰瑞科技汇

Java如何获取当前时间戳?

Java获取当前时间的时间戳

在Java中,获取当前时间的时间戳有几种常见方法:

Java如何获取当前时间戳?-图1
(图片来源网络,侵删)

使用 System.currentTimeMillis()

这是最简单直接的方法,返回自1970年1月1日00:00:00 UTC以来的毫秒数。

long timestamp = System.currentTimeMillis();
System.out.println("当前时间戳(毫秒): " + timestamp);

使用 Instant 类 (Java 8+)

Instant 类表示时间线上的一个瞬时点,更精确到纳秒。

import java.time.Instant;
Instant instant = Instant.now();
long timestamp = instant.toEpochMilli(); // 获取毫秒级时间戳
System.out.println("当前时间戳(毫秒): " + timestamp);
long nanosTimestamp = instant.getEpochSecond() * 1000000000L + instant.getNano(); // 纳秒级时间戳
System.out.println("当前时间戳(纳秒): " + nanosTimestamp);

使用 Date

import java.util.Date;
Date date = new Date();
long timestamp = date.getTime();
System.out.println("当前时间戳(毫秒): " + timestamp);

使用 Calendar

import java.util.Calendar;
Calendar calendar = Calendar.getInstance();
long timestamp = calendar.getTimeInMillis();
System.out.println("当前时间戳(毫秒): " + timestamp);

注意事项

  1. System.currentTimeMillis() 是性能最高的方法,适合只需要时间戳的场景
  2. Instant 类是Java 8引入的新API,功能更强大,推荐在新项目中使用
  3. 时间戳通常是毫秒级的,但也可以获取纳秒级(使用System.nanoTime()Instant.getNano()
  4. 时间戳的起点是Unix纪元(1970-01-01 00:00:00 UTC)

示例:获取不同精度的时间戳

public class TimestampExample {
    public static void main(String[] args) {
        // 毫秒级时间戳
        long millis = System.currentTimeMillis();
        System.out.println("毫秒级时间戳: " + millis);
        // 纳秒级时间戳
        long nanos = System.nanoTime();
        System.out.println("纳秒级时间戳: " + nanos);
        // 使用Instant获取纳秒级时间戳
        Instant instant = Instant.now();
        long instantNanos = instant.getEpochSecond() * 1000000000L + instant.getNano();
        System.out.println("Instant纳秒级时间戳: " + instantNanos);
    }
}

选择哪种方法取决于你的具体需求,对于大多数应用场景,System.currentTimeMillis()Instant.now() 就足够了。

Java如何获取当前时间戳?-图2
(图片来源网络,侵删)
分享:
扫描分享到社交APP
上一篇
下一篇