最推荐使用Instant.now().toEpochMilli()获取时间戳,1. System.currentTimeMillis()高效简单;2. Date().getTime()已过时;3. Instant支持纳秒且线程安全;4. LocalDateTime需结合时区转换。

在 Java 中获取当前时间戳有多种方式,适用于不同的场景和需求。以下是几种常用的方法,涵盖从传统到现代的时间处理方式。
示例代码:
立即学习“Java免费学习笔记(深入)”;
long timestamp = System.currentTimeMillis();
System.out.println("当前时间戳(毫秒): " + timestamp);
示例代码:
立即学习“Java免费学习笔记(深入)”;
import java.util.Date;
Date date = new Date();
long timestamp = date.getTime();
System.out.println("当前时间戳(毫秒): " + timestamp);
示例代码:
立即学习“Java免费学习笔记(深入)”;
import java.time.Instant;
Instant now = Instant.now();
long timestamp = now.toEpochMilli(); // 毫秒
long secondTimestamp = now.getEpochSecond(); // 秒
System.out.println("毫秒时间戳: " + timestamp);
System.out.println("秒级时间戳: " + secondTimestamp);
示例代码:
立即学习“Java免费学习笔记(深入)”;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
LocalDateTime now = LocalDateTime.now();
long timestamp = now.toEpochSecond(ZoneOffset.UTC);
System.out.println("秒级时间戳: " + timestamp);
以上就是java怎么获取当前时间戳 获取当前时间戳的多种方式的详细内容,更多请关注php中文网其它相关文章!
 
                        
                        java怎么学习?java怎么入门?java在哪学?java怎么学才快?不用担心,这里为大家提供了java速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
 
                Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号