如何计算日期差?
问题描述
我正在使用java.util.Date
类,并且想要比较date
对象和当前时间。
输出格式必须是这样:
"... years , ... months , ... days , ...hours , ... minutes , ... seconds.
这是我的代码:
public static void main(String[] args) {
Calendar calendar = new GregorianCalendar(2022, 1 , 25 , 12 , 20 , 33);
Date now = new Date(); //Tue Feb 25 11:49:05 IRST 2020
Date date = calendar.getTime(); //Fri Feb 25 12:20:33 IRST 2022
}
有一种简单的方法可以计算出来吗?
思路一:
Java 8 Date/Time API在比较日期方面很灵活。
示例:
LocalDate currentDate = LocalDate.now();
LocalDate previousDate = LocalDate.of(2000, 7, 1);
assertThat(currentDate.isAfter(previousDate), is(true));
更多示例here。
思路二:
使用Java Instant
Instant start, end;
Duration duration = Duration.between(start, stop);
long hours = dur.toHours();
long minutes = dur.toMinutes();
思路三:
由于年,月和日的不同,有一个
java.time.Period
您可以轻松地使用它来获取所需的内容:public static void main(String[] args) {
LocalDateTime localDateTime = LocalDateTime.of(2022, 1 , 25 , 12 , 20 , 33);
LocalDateTime now = LocalDateTime.now();
// get the difference in years, months and days
Period p = Period.between(now.toLocalDate(), localDateTime.toLocalDate());
// and print the result(s)
System.out.println("Difference between " + localDateTime.format(DateTimeFormatter.ISO_LOCAL_DATE_TIME)
+ " and " + now.format(DateTimeFormatter.ISO_LOCAL_DATE_TIME) + " is:\n"
+ p.getYears() + " years, " + p.getMonths() + " months, " + p.getDays() + " days");
}
此代码示例的输出将是(当然,取决于当天):
Difference between 2022-01-25T12:20:33 and 2020-02-25T10:52:43.327 is: 1 years, 11 months, 0 days
上一篇:无法识别ADB命令
下一篇:战略设计模式与实施行为之间的差异