How to get number of days between two calendar instance?

后端 未结 11 1119
孤城傲影
孤城傲影 2020-12-05 01:58

I want to find the difference between two Calendar objects in number of days if there is date change like If clock ticked from 23:59-0:00 there should be a day

11条回答
  •  悲哀的现实
    2020-12-05 02:54

    UPDATE The Joda-Time project, now in maintenance mode, advises migration to the java.time classes. See the Answer by Anees A for the calculation of elapsed hours, and see my new Answer for using java.time to calculate elapsed days with respect for the calendar.

    Joda-Time

    The old java.util.Date/.Calendar classes are notoriously troublesome and should be avoided.

    Instead use the Joda-Time library. Unless you have Java 8 technology in which case use its successor, the built-in java.time framework (not in Android as of 2015).

    Since you only care about "days" defined as dates (not 24-hour periods), let's focus on dates. Joda-Time offers the class LocalDate to represent a date-only value without time-of-day nor time zone.

    While lacking a time zone, note that time zone is crucial in determining a date such as "today". A new day dawns earlier to the east than to the west. So the date is not the same around the world at one moment, the date depends on your time zone.

    DateTimeZone zone = DateTimeZone.forID ( "America/Montreal" );
    LocalDate today = LocalDate.now ( zone );
    

    Let's count the number of days until next week, which should of course be seven.

    LocalDate weekLater = today.plusWeeks ( 1 );
    int elapsed = Days.daysBetween ( today , weekLater ).getDays ();
    

    The getDays on the end extracts a plain int number from the Days object returned by daysBetween.

    Dump to console.

    System.out.println ( "today: " + today + " to weekLater: " + weekLater + " is days: " + days );
    

    today: 2015-12-22 to weekLater: 2015-12-29 is days: 7

    You have Calendar objects. We need to convert them to Joda-Time objects. Internally the Calendar objects have a long integer tracking the number of milliseconds since the epoch of first moment of 1970 in UTC. We can extract that number, and feed it to Joda-Time. We also need to assign the desired time zone by which we intend to determine a date.

    long startMillis = myStartCalendar.getTimeInMillis();
    DateTime startDateTime = new DateTime( startMillis , zone );
    
    long stopMillis = myStopCalendar.getTimeInMillis();
    DateTime stopDateTime = new DateTime( stopMillis , zone );
    

    Convert from DateTime objects to LocalDate.

    LocalDate start = startDateTime.toLocalDate();
    LocalDate stop = stopDateTime.toLocalDate();
    

    Now do the same elapsed calculation we saw earlier.

    int elapsed = Days.daysBetween ( start , stop ).getDays ();
    

提交回复
热议问题