
Java如何获取一个时间的数据
用户关注问题
我需要在Java程序中获取当前时间的时间戳,该怎么做?
使用System.currentTimeMillis()获取时间戳
可以使用System.currentTimeMillis()方法获取当前时间距离1970年1月1日00:00:00 UTC的毫秒数,这个值即为时间戳。示例代码:long timestamp = System.currentTimeMillis();
想要得到类似“2024-06-01 12:30:45”格式的当前时间字符串,应如何实现?
使用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);
我有一个时间对象,想分别获取它的年、月、日,应该用哪些方法?
使用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)即可。