Date from = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse("2023-04-16 17:17:00");
Instant end = from.toInstant();
Instant now = new Date().toInstant();
Long day = ChronoUnit.DAYS.between(end, now);
Long seconds = ChronoUnit.SECONDS.between(end, now);
Long hours = ChronoUnit.HOURS.between(end, now);
Long minutes = ChronoUnit.MINUTES.between(end, now);
//在ChronoUnit中 还有更多其他类型的
System.out.println(
"相差天数为:" + day +
" 小时为:" + hours +
" 分钟为:" + minutes +
" 秒为:" + seconds
);
打印输出:
相差天数为:2 小时为:48 分钟为:2884 秒为:173062
该代码段展示了如何使用Java的SimpleDateFormat解析日期字符串,将其转换为Instant对象,然后计算两个Instant之间的时间差,分别以天、小时、分钟和秒为单位。输出显示了从指定日期到当前时间的差距。

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



