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()//天数