Dayananda
Dayananda

Reputation: 732

How to find the time difference when time is given

I have the time in the following format.

String deptTime ="08:00 PM";
String arrTime = "04:00 AM";

How to get the difference hours exactly in words like 1 hour 30 minutes ..

Upvotes: 1

Views: 133

Answers (2)

Dayananda
Dayananda

Reputation: 732

use apache commons-lang jar file.. Take the deptTime and arrTime as StringBuffer

    SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
    Calendar calendar = Calendar.getInstance();
    String dateIs = dateFormat.format(calendar.getTime());
    if (departureTime.reverse().substring(0,2).equalsIgnoreCase(arrivalTime.reverse().substring(0,2))) {
        departureTime.reverse().insert(0, dateIs + " ");
        arrivalTime.reverse().insert(0, dateIs + " ");
    } else {
        departureTime.reverse().insert(0, dateIs + " ");
        calendar.add(Calendar.DATE, 1);
        arrivalTime.reverse().insert(0,dateFormat.format(calendar.getTime()) +" ");
    }
    dateFormat.applyPattern("dd/MM/yyyy hh:mm aa");
    Date dateOne = dateFormat.parse(departureTime.toString());
    Date dateTwo = dateFormat.parse(arrivalTime.toString());

    DurationFormatUtils.formatDurationHMS(dateTwo.getTime() - dateOne.getTime());
    System.out.println(DurationFormatUtils.formatDurationWords(dateTwo.getTime() -
                                                               dateOne.getTime(),
                                                               true, true));

Upvotes: 0

Pramod Kumar
Pramod Kumar

Reputation: 8014

    Calendar cal1 = Calendar.getInstance();
    cal1.set(Calendar.HOUR, 8);
    cal1.set(Calendar.AM_PM, Calendar.PM);


    Calendar cal2 = Calendar.getInstance();
    cal2.set(Calendar.HOUR, 4);
    cal2.set(Calendar.AM_PM, Calendar.AM);
    System.out.println(((cal1.getTimeInMillis()-cal2.getTimeInMillis())/1000)/3600);

Upvotes: 1

Related Questions