Difference in days between two dates in Java?

后端 未结 19 1968
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-11-22 08:26

I need to find the number of days between two dates: one is from a report and one is the current date. My snippet:

  int age=calculateDiffer         


        
19条回答
  •  梦如初夏
    2020-11-22 08:45

    java.time

    In Java 8 and later, use the java.time framework (Tutorial).

    Duration

    The Duration class represents a span of time as a number of seconds plus a fractional second. It can count days, hours, minutes, and seconds.

    ZonedDateTime now = ZonedDateTime.now();
    ZonedDateTime oldDate = now.minusDays(1).minusMinutes(10);
    Duration duration = Duration.between(oldDate, now);
    System.out.println(duration.toDays());
    

    ChronoUnit

    If all you need is the number of days, alternatively you can use the ChronoUnit enum. Notice the calculation methods return a long rather than int.

    long days = ChronoUnit.DAYS.between( then, now );
    

提交回复
热议问题