0

I have two times, a start and a stop time, in the format of 05:00 (HH:MM). I need the difference between the two times.Suppose if start time is 05:00 and end time is 15:20, then how do I calculate the time difference between two which will be 10 Hours 20 minutes. Should I convert them into datetime object and use the milliseconds to get the time difference or is there any better approach to do this?

Gopakumar N G
  • 1,775
  • 1
  • 23
  • 40
Ansh
  • 2,366
  • 3
  • 31
  • 51

1 Answers1

6

Use Joda Time. You want the LocalTime type to represent your start and stop times, then create a Period between them.

I don't know whether there's a cut-down version of Joda Time available for Android (it may be a little big otherwise, if your app is otherwise small) but it will make things much simpler than using the plain JDK libraries. You can do that, of course - converting both into milliseconds, finding the difference and then doing the arithmetic. It would just be relatively painful :(

Sample code:

import org.joda.time.*;

public class Test {    
    public static void main(String args[]) {
        LocalTime start = new LocalTime(5, 0);
        LocalTime end = new LocalTime(15, 20);
        Period period = new Period(start, end, PeriodType.time());
        System.out.println(period.getHours()); // 10
        System.out.println(period.getMinutes()); // 20        
    }
}

And just using JDK classes:

import java.util.*;
import java.util.concurrent.*;
import java.text.*;

public class Test {    
    public static void main(String args[]) throws ParseException {
        DateFormat format = new SimpleDateFormat("HH:mm", Locale.US);
        format.setTimeZone(TimeZone.getTimeZone("UTC"));
        Date start = format.parse("05:00");
        Date end = format.parse("15:20");

        long difference = end.getTime() - start.getTime();

        long hours = TimeUnit.MILLISECONDS.toHours(difference);
        long minutes = TimeUnit.MILLISECONDS.toMinutes(difference) % 60;

        System.out.println("Hours: " + hours);
        System.out.println("Minutes: " + minutes);
    }
}

Note that this assumes that end is after start - you'd need to work out the desired results for negative times.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • Wouldn't Joda time be over kill for this? – Ansh May 27 '13 at 08:58
  • 1
    @user818455: It depends on how much you value your code's simplicity. You'll save time by using Joda Time, but it's obviously an extra dependency. Do you do other date/time work in your app? The more date/time work you do, the more sense it makes to use Joda Time. – Jon Skeet May 27 '13 at 09:00
  • @user818455: See my edit for a JDK-based version. – Jon Skeet May 27 '13 at 09:03
  • Now I will definitely go for Joda time as I have more work to do with date/time.Thanks @Jon – Ansh May 27 '13 at 09:04