Search code examples
androidandroid-timepicker

Difference between two Times in Minutes are coming as negative


I have a method which takes two String parameters. the two strings are Time values in 24 hour format. The Times are picked using a TimePicker from UI.

The goal of the method is to get the duration between the StartTime and EndTime in Minutes.

public static String getTimeDuration(String StartTime24, String EndTime24)
{
    String duration = "";

    try 
    {
        SimpleDateFormat parseFormat = new SimpleDateFormat("HH:mm");
        Date startTime = parseFormat.parse(StartTime24);
        Date endTime = parseFormat.parse(EndTime24);

        long mills = endTime.getTime() - startTime.getTime();
        long minutes = mills/(1000 * 60);

        duration = "(" + minutes + " Minutes)";
    }
    catch(ParseException ex)
    {
        // exception handling here
    }

    return duration;
}

The method works fine if both the times are within a Single Date. For example:

StartTime = 22:15
EndTime = 23:51
Output = (96 Minutes)

But my problem is, the method returns negative if the end time is after 12'o clock at night. For example,

StartTime = 23:51
EndTime = 0:55
Output = (-1376 Minutes)
What I want: (64 Minutes)

How can get the duration correct ?


Solution

  • As there is no date used, you have to check first if your endTime is less than your startTime. If yes, then your endTime is on the next day and you have to add 1 day/86 400 000 milliseconds. Then you will have your desired result.

    Just add this condition:

    if(endTime.getTime() < startTime.getTime()){  
    
       long mills = ((endTime.getTime() + 86400000) - startTime.getTime());  1 day = 86 400 000 mill
    
    }
    

    Hope this helps