【问题标题】:How to calculate the difference of dates?如何计算日期的差异?
【发布时间】:2020-02-25 09:43:01
【问题描述】:

我正在使用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
}

有没有简单的计算方法?

【问题讨论】:

  • 一年有多长?一个月有多长?一天有多长?一个小时有多长?一分钟有多长?答案可能会让你大吃一惊! infiniteundo.com/post/25326999628/… 如果您愿意假设“1 年 = 365 天”等等,那么您只需减去 Date#getTime() 的值即可得到以毫秒为单位的差异,然后从那里开始。
  • 如果你比较"2020-25-02 12:00:00""2020-25-02 13:20:10",输出应该是"1 hour, 20 minutes, 10 seconds"还是"1 hour, 140 minutes, 3610 seconds"
  • 我建议你不要使用CalendarDate。这些课程设计不佳且早已过时。而是使用例如来自java.time, the modern Java date and time APILocalDateTime
  • 还可以查看 ThreeTen Extra 项目的 PeriodDuration 类。

标签: java datetime date-difference


【解决方案1】:

java.timewhy & how to use it

对于年、月、日的差异,有一个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

您可以使用java.time.Duration,如其他答案之一所示,以获得小时、分钟和秒的额外差异。看这个例子(基本上是上面加时间的计算):

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 (date related difference)
    Period p = Period.between(now.toLocalDate(), localDateTime.toLocalDate());
    // and the difference in hours, minutes and seconds (time-of-day related difference)
    Duration d = Duration.between(now.toLocalTime(), localDateTime.toLocalTime());
    long totalSeconds = d.getSeconds();
    long hours = totalSeconds / 3600;
    long minutes = (totalSeconds % 3600) / 60;
    long seconds = totalSeconds % 60;

    // 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, "
            + hours + " hours, " + minutes + " minutes, " + seconds + " seconds");
}

输出:

Difference between 2022-01-25T12:20:33 and 2020-02-25T11:25:42.712 is:
1 years, 11 months, 0 days, 0 hours, 54 minutes, 50 seconds

如果您正在接收java.util.Dates 或扩展遗留代码(或者如果您懒得将所有代码更改为使用java.time),您可以使用以下兼容方法:

LocalDateTime fromDate = LocalDateTime.ofInstant(new Date().toInstant(), ZoneId.systemDefault());
Date fromLocalDateTime = Date.from(LocalDateTime.now().toInstant((ZoneOffset.UTC)));

【讨论】:

    【解决方案2】:

    Java 8 Date/Time API 在比较日期方面很灵活。

    例子:

    LocalDate currentDate = LocalDate.now();
    LocalDate previousDate = LocalDate.of(2000, 7, 1);
    
    Period period = Period.between(previousDate, currentDate);
    
    String output = String.format("%s years , %s months , %s days",
                    period.getYears(), period.getMonths(), period.getDays());
    
    System.out.println(output);   
    > 19 years , 7 months , 24 days
    

    更多示例here

    如果您想在PeriodDuration 之间做出选择,This 可能会对您有所帮助。

    【讨论】:

      【解决方案3】:

      使用 java Instant

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-09-15
        • 2017-10-16
        • 2013-09-02
        • 2011-12-07
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多