Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to get minutes difference between two time in android

public int difftime(String string, String string2) {
        int hours;
        int min = 0;
        int days;
        long difference ;
        try {
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("HH:mm");
            Date date1 = simpleDateFormat.parse("08:00 AM");
            Date date2 = simpleDateFormat.parse("04:00 PM");

             difference = date2.getTime() - date1.getTime();
             days = (int) (difference / (1000 * 60 * 60 * 24));
            hours = (int) ((difference - (1000 * 60 * 60 * 24 * days)) / (1000 * 60 * 60));
             min = (int) (difference - (1000 * 60 * 60 * 24 * days) - (1000 * 60 * 60 * hours))
                    / (1000 * 60);
            hours = (hours < 0 ? -hours : hours);
            Log.i("======= Hours", " :: " + hours);
            return min;
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        return min;
    }

This is my function to get time difference in the form of minutes but it give always zero. I don't know where i did mistake please tell me where am doing mistake. I want result in the form of minutes.

like image 798
Research Development Avatar asked Sep 10 '25 22:09

Research Development


1 Answers

First of all, you did very basic mistake. For 12-hour system, you should use hh not HH. And I am amazed to see that, none of the answers correct this mistake.

Secondly, you're not considering Date rather only depending upon the time. So 08:00AM and 04:00PM doesn't have any minute difference. It only have 8 hours difference.

So, now in your case, you have to calculate minutes based on two scenarios i-e one from Hours and one when there is minutes difference. I correct your code. Please Check it as this is working as expected at my end.

public long diffTime() {
    long min = 0;
    long difference ;
    try {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("hh:mm aa"); // for 12-hour system, hh should be used instead of HH
        // There is no minute different between the two, only 8 hours difference. We are not considering Date, So minute will always remain 0
        Date date1 = simpleDateFormat.parse("08:00 AM");
        Date date2 = simpleDateFormat.parse("04:00 PM");

        difference = (date2.getTime() - date1.getTime()) / 1000;
        long hours = difference % (24 * 3600) / 3600; // Calculating Hours
        long minute = difference % 3600 / 60; // Calculating minutes if there is any minutes difference
        min = minute + (hours * 60); // This will be our final minutes. Multiplying by 60 as 1 hour contains 60 mins
    } catch (Throwable e) {
        e.printStackTrace();
    }
    return min;
}
like image 170
Yasir Tahir Avatar answered Sep 13 '25 11:09

Yasir Tahir