java里如何获取时间

java里如何获取时间

作者:Rhett Bai发布时间:2026-02-09阅读时长:0 分钟阅读次数:23

用户关注问题

Q
如何在Java中获取当前系统时间?

我想在Java程序中获取当前的系统时间,该怎么实现?

A

使用System类或Date类获取当前系统时间

可以使用System.currentTimeMillis()方法获取当前时间的毫秒数,也可以使用java.util.Date类创建一个新的Date对象,表示当前时间。例如:

long currentTimeMillis = System.currentTimeMillis();
Date currentDate = new Date();
Q
Java中如何获取格式化后的当前时间?

获取当前时间后,怎样将时间格式化为指定的字符串形式?

A

使用SimpleDateFormat类进行时间格式化

可以用java.text.SimpleDateFormat类将时间格式化为想要的字符串。例如,要以“yyyy-MM-dd HH:mm:ss”格式输出当前时间:

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String formattedDate = sdf.format(new Date());
Q
Java 8及以上版本怎样更方便地获取当前时间?

Java 8引入了新的时间API,如何利用这些新特性获取当前时间?

A

使用java.time包中的LocalDateTime和Instant类

Java 8及后续版本推荐使用java.time包中的类。可以使用LocalDateTime.now()获取当前本地时间,或者用Instant.now()获取UTC时间。例如:

LocalDateTime now = LocalDateTime.now();
Instant instantNow = Instant.now();