杰瑞科技汇

Java timestamp如何获取当前时间?

在 Java 中,获取当前时间戳有多种方式,主要分为 Unix 时间戳(秒/毫秒)Java 8+ 的 Instant,以下是几种常见的方法:

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

使用 System.currentTimeMillis()(推荐)

获取当前时间的 毫秒级时间戳(从 1970-01-01 00:00:00 UTC 开始计算的毫秒数)。

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

转换为秒级时间戳

long seconds = timestamp / 1000;
System.out.println("当前时间戳(秒): " + seconds);

使用 System.nanoTime()

获取 纳秒级时间戳(用于高精度计时,但不适合表示时间点)。

long nanos = System.nanoTime();
System.out.println("当前纳秒时间戳: " + nanos);

使用 java.time.Instant(Java 8+ 推荐)

Java 8 引入了 java.time 包,Instant 表示时间线上的一个点(UTC 时间)。

获取当前时间的 Instant

import java.time.Instant;
Instant now = Instant.now();
System.out.println("当前 Instant: " + now);

转换为毫秒/秒时间戳

long millis = now.toEpochMilli();  // 毫秒时间戳
long seconds = now.getEpochSecond(); // 秒时间戳
System.out.println("毫秒时间戳: " + millis);
System.out.println("秒时间戳: " + seconds);

使用 java.util.Date(旧版)

Date 类已过时,但仍然可以使用。

Java timestamp如何获取当前时间?-图2
(图片来源网络,侵删)
import java.util.Date;
Date date = new Date();
long timestamp = date.getTime(); // 毫秒时间戳
System.out.println("当前时间戳: " + timestamp);

使用 java.time.LocalDateTime(Java 8+)

如果需要本地时间(非 UTC),可以使用 LocalDateTime

import java.time.LocalDateTime;
import java.time.ZoneOffset;
LocalDateTime now = LocalDateTime.now();
long timestamp = now.toEpochSecond(ZoneOffset.UTC) * 1000; // 转换为毫秒时间戳
System.out.println("当前时间戳(本地时间): " + timestamp);

方法 返回类型 说明
System.currentTimeMillis() long 毫秒时间戳(推荐)
System.nanoTime() long 纳秒时间戳(用于计时)
Instant.now().toEpochMilli() long 毫秒时间戳(Java 8+ 推荐)
new Date().getTime() long 毫秒时间戳(旧版)
LocalDateTime.now().toEpochSecond() long 本地时间时间戳(Java 8+)

推荐用法

  • 如果只需要时间戳System.currentTimeMillis()(最快)。
  • 如果使用 Java 8+Instant.now()(更现代化)。
  • 如果需要本地时间LocalDateTime.now()

希望这能帮到你!如果有其他需求,欢迎继续提问。 😊

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