public static void main(String[] args) {
// 字符串转LocalDateTime
DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
LocalDateTime endTime = LocalDateTime.parse("2021-11-12 17:21:35",df);
// 当前时间
LocalDateTime time = LocalDateTime.now();
System.out.println("当前时间是否大于指定时间:"+ time.isAfter(endTime));
System.out.println("年:"+endTime.getYear() +" 月:" + endTime.getMonthValue());
System.out.println("日:"+endTime.getDayOfMonth() +" 时:" + endTime.getHour());
System.out.println("分:"+endTime.getMinute() +" 秒:" + endTime.getSecond());
// LocalDateTime转字符串
String localTime = df.format(time);
System.out.println("字符串时间:"+ localTime);
}
结果:
当前时间是否大于指定时间:true
年:2021 月:11
日:12 时:17
分:21 秒:35
字符串时间:2021-11-15 11:05:18
计算时间差:
LocalDateTime.now() 获得当前时间
java.time.Duration duration = java.time.Duration.between(LocalDateTime startTime, LocalDateTime endTime );
例如: duration.toMinutes() //两个时间差的分钟数
toNanos()//纳秒
toMillis()//毫秒
toMinutes()//分钟
toHours()//小时
toDays()//天数
该博客演示了如何在Java中将字符串转换为LocalDateTime对象,并进行时间比较。它还展示了获取时间字段的方法,并提供了计算时间差的API示例,如Duration.between()用于计算两个时间点之间的差距。
2877

被折叠的 条评论
为什么被折叠?



