浅显易懂的Java LocalDateTime日期时间详解
LocalDateTime是Java 8中用于表示日期时间的类,它包含了多个方法用于获取
、操作
和格式化
日期时间。下面详细列出在开发中常用的相关方法。
1. 获取当前日期时间
使用 now()
方法获取当前日期时间。
LocalDateTime currentDateTime = LocalDateTime.now();
System.out.println("当前日期时间:" + currentDateTime);
2. 获取指定日期时间的年、月、日、时、分、秒
使用 getYear()
、 getMonthValue()
、 getDayOfMonth()
、 getHour()
、 getMinute()
、 getSecond()
方法分别获取年、月、日、时、分、秒。
LocalDateTime currentDateTime = LocalDateTime.now();
int year = currentDateTime.getYear();
int month = currentDateTime.getMonthValue();
int day = currentDateTime.getDayOfMonth();
int hour = currentDateTime.getHour();
int minute = currentDateTime.getMinute();
int second = currentDateTime.getSecond();
System.out.println("年:" + year + ",月:" + month + ",日:" + day + ",时:" + hour + ",分:" + minute + ",秒:" + second);
3. 设置日期时间的年、月、日、时、分、秒
使用 withYear()
、 withMonth()
、 withDayOfMonth()
、 withHour()
、 withMinute()
、 withSecond()
方法设置年、月、日、时、分、秒。
LocalDateTime newDateTime = currentDateTime.withYear(2023).withMonth(9).withDayOfMonth(15).withHour(14).withMinute(30).withSecond(45);
System.out.println("新日期时间:" + newDateTime);
4. 日期时间比较
两个日期时间的比较可以使用 isBefore()
、 isAfter()
、 isEqual()
方法进行日期时间的比较
。
LocalDateTime futureDateTime = LocalDateTime.of(2022, 12, 31, 23, 59, 59);
if (currentDateTime.isBefore(futureDateTime)) {
System.out.println("当前日期时间早于未来日期时间");
}
5. 格式化日期时间
使用 format()
方法和 DateTimeFormatter
类进行日期时间的格式化。
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
String formattedDateTime = currentDateTime.format(formatter);
System.out.println("格式化后的日期时间:" + formattedDateTime);
上一篇 Java中的日期时间类详解(建议收藏)!!! |
记得点赞收藏哦!!!
| 下一篇 synchronized是如何保证代码同步的!!! |