浅显易懂的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是如何保证代码同步的!!!
  • 5
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值