Java如何获取一个时间的数据

Java如何获取一个时间的数据

作者:William Gu发布时间:2026-02-10阅读时长:0 分钟阅读次数:13

用户关注问题

Q
如何在Java中获取当前时间的时间戳?

我需要在Java程序中获取当前时间的时间戳,该怎么做?

A

使用System.currentTimeMillis()获取时间戳

可以使用System.currentTimeMillis()方法获取当前时间距离1970年1月1日00:00:00 UTC的毫秒数,这个值即为时间戳。示例代码:long timestamp = System.currentTimeMillis();

Q
Java中如何获取当前日期和时间的格式化字符串?

想要得到类似“2024-06-01 12:30:45”格式的当前时间字符串,应如何实现?

A

使用DateTimeFormatter和LocalDateTime实现时间格式化

可以通过Java 8及以上版本的java.time包实现时间格式化。示例代码如下:
LocalDateTime now = LocalDateTime.now();
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
String formattedDateTime = now.format(formatter);

Q
如何在Java中获取指定时间的年、月、日信息?

我有一个时间对象,想分别获取它的年、月、日,应该用哪些方法?

A

使用LocalDate或者Calendar获取时间的年、月、日

如果使用java.time包的LocalDate,可以直接调用getYear()、getMonthValue()和getDayOfMonth()方法。示例:
LocalDate date = LocalDate.of(2024, 6, 1);
int year = date.getYear();
int month = date.getMonthValue();
int day = date.getDayOfMonth();
如果使用旧版的Calendar类,则调用get(Calendar.YEAR)、get(Calendar.MONTH)和get(Calendar.DAY_OF_MONTH)即可。