如何计算日期差?

问题描述 投票:0回答:2

我正在使用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 datetime date-difference
2个回答
0
投票
Java 8 Date/Time API在比较日期方面很灵活。

示例:

LocalDate currentDate = LocalDate.now(); LocalDate previousDate = LocalDate.of(2000, 7, 1); assertThat(currentDate.isAfter(previousDate), is(true));

更多示例here

0
投票
使用Java Instant

Instant start, end; Duration duration = Duration.between(start, stop); long hours = dur.toHours(); long minutes = dur.toMinutes();


0
投票
由于年,月和日的不同,有一个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

© www.soinside.com 2019 - 2024. All rights reserved.