import java.time.Duration;import java.time.LocalDateTime;import java.time.format.DateTimeFormatter;import java.util.Scanner;/*** 计算当前时间到指定日期之间距离多久* @author silence*/public class Demo3 {public static void main(String[] args) {Scanner scanner = new Scanner(System.in);DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-M-d HH:mm:ss");LocalDateTime end = null;while (true) {System.out.println("请输入日期:(列:1970-01-01)");String next = scanner.next();try {//格式化结束时间,提供默认时间输入日期的0时0分0秒end = LocalDateTime.parse(next + " 00:00:00", formatter);} catch (Exception e) {System.out.println("输入的日期格式错误,请输入正确的日期格式如:1970-01-01");continue;}//获得当前时间LocalDateTime start = LocalDateTime.now();//计算时间间隔Duration between = Duration.between(start,end );//获取此持续时间内的天数long days = between.toDays();//获取此持续时间内的小时数。long hours = between.toHours();//获取此持续时间的分钟数。long minutes = between.toMinutes();//获取此持续时间内的秒数。long seconds = between.getSeconds();//如果输入的时间大于当前的分钟,重新输入if (minutes <= 0) {System.out.println("不能输入当前时间之前的日期时间");continue;}System.out.println("距离输入的日期还有::" + days + "天" + hours + "小时" + minutes + "分钟"+seconds+"秒");break;}}}
如果觉得《计算当前时间到指定日期之间距离多久(494天11866小时711960分钟42717625秒)》对你有帮助,请点赞、收藏,并留下你的观点哦!