Search code examples
javadatetimegregorian-calendar

How to get duration by subtracting Arrival time by departing time in Java using Gregorian calendar?


Lets say I have to subtract Arrival time by departing time of specific days. How would I do this in Java using Gregorian calendar?

public Duration getDuration(){
  SimpleDateFormat date = new SimpleDateFormat("YYYYMMDD");
  SimpleDateFormat time = new SimpleDateFormat("HHMM");

  String ArivalTime = "1720"
  String DepartingTime = "1100"
  String ArivalDate = "20200220"
  String DepartingDate = "20200211"

  Calendar departureDateCalc = new GregorianCalendar();


  //return duration;
}

the code is barely anything. But I need to subtract an Arrival date by Departing date


Solution

  • java.time

    Don’t use GregorianCalendar for this. Use java.time, the modern Java date and time API.

        DateTimeFormatter timeFormatter = DateTimeFormatter.ofPattern("HHmm");
    
        String arrivalTime = "1720";
        String departingTime = "1100";
        String arrivalDate = "20200220";
        String departingDate = "20200211";
        String arrivalTimeZone = "Africa/Niamey";
        String departingTimeZone = "America/Mendoza";
    
        ZonedDateTime departure = LocalDate.parse(departingDate, DateTimeFormatter.BASIC_ISO_DATE)
                .atTime(LocalTime.parse(departingTime, timeFormatter))
                .atZone(ZoneId.of(departingTimeZone));
        ZonedDateTime arrival = LocalDate.parse(arrivalDate, DateTimeFormatter.BASIC_ISO_DATE)
                .atTime(LocalTime.parse(arrivalTime, timeFormatter))
                .atZone(ZoneId.of(arrivalTimeZone));
    
        Duration difference = Duration.between(departure, arrival);
        System.out.println(difference);
    

    This outputs:

    PT218H20M

    So a period of time of 218 hours 20 minutes. If you want it more readable:

        String diffString = String.format(
                "%d days %d hours %d minutes", difference.toDays(),
                difference.toHoursPart(), difference.toMinutesPart());
        System.out.println(diffString);
    

    9 days 2 hours 20 minutes

    The conversion to days assumes that a day is always 24 hours, which may not be the case in either of the departure or the arrival time zone, for example when they go from standard to summer time (DST) or vice versa.

    Don’t use GregorianCalendar

    The GregorianCalendar class is poorly designed and long outdated. Don’t use it. For anything. If you had wanted to use it for finding a duration, the way would have been to add one day at a time to the departure time until you reach the arrival time. If you’re past it, subtract one day again and start counting hours, again by adding one at a time. Same with minutes. It’s way more complicated and also more error-prone than using the Duration class directly.

    Link

    Oracle tutorial: Date Time explaining how to use java.time.