16

I have two string variables such as StartTime and EndTime. I need to Calculate the TotalTime by subtracting the EndTime with StartTime.

The Format of StartTime and EndTime is as like follows:

StartTime = "08:00 AM";
EndTime = "04:00 PM";

TotalTime in Hours and Mins Format. How to calculate this in Android?

Nithin Michael
  • 2,166
  • 11
  • 32
  • 56
Munazza
  • 735
  • 3
  • 9
  • 22

8 Answers8

49

Try below code.

// suppose time format is into ("hh:mm a") format

SimpleDateFormat simpleDateFormat = new SimpleDateFormat("hh:mm a");

date1 = simpleDateFormat.parse("08:00 AM");
date2 = simpleDateFormat.parse("04:00 PM");

long 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);

Output - Hours :: 8

Alok Mishra
  • 1,904
  • 1
  • 17
  • 18
Chirag
  • 56,621
  • 29
  • 151
  • 198
  • Hey thank u , the difference is always negative, my start time was 12:30 PM and end time was 1:00 PM. i have given it the format as "HH:mm a" and the difference is still negative. Althogh end time is greater than the start time. – Munazza Jan 01 '13 at 13:30
  • Do I need to give the date with string as well? – Munazza Jan 01 '13 at 13:31
  • use 01:00 PM instead of 1:00 PM and try what happend . – Chirag Jan 02 '13 at 06:32
  • i have tried both but the hours difference is negavtive , even if I try 08:00 AM and 04:00 PM it returns minutes and hours as 0.0.I am doingit like this SimpleDateFormat simpleDateFormat = new SimpleDateFormat("HH:mm a"); Date date1 = simpleDateFormat.parse("08:00 AM"); Date date2 = simpleDateFormat.parse("04:00 PM"); long difference = date1.getTime() - date2.getTime(); int days = (int) (difference / (1000*60*60*24)); int hours = (int) ((difference - (1000*60*60*24*days)) / (1000*60*60)); int min = (int) (difference - (1000*60*60*24*days) - (1000*60*60*hours)) / (1000*60); – Munazza Jan 03 '13 at 07:50
  • @Munazza Here i post code after try by my self and i get result that i also log here. – Chirag Jan 03 '13 at 08:31
  • @Chiragh , the type of date1 and date2 is Date ? – Munazza Jan 03 '13 at 09:59
  • @Munazza Yes, it must be date. – Chirag Jan 03 '13 at 10:11
  • date1 = simpleDateFormat.parse("08:00 AM"); date2 = simpleDateFormat.parse("04:00 PM"); When i debug After this point the date1 and date2 's milliseconds are -180000000 , thats so strange that u are getting correct output with the same code :( – Munazza Jan 03 '13 at 10:17
  • I get value of difference is 0 @Chirag – Brinda Rathod Oct 08 '18 at 07:01
  • This is very old code, so i need to check this code and if anything wrong then i will update the code – Chirag Oct 09 '18 at 14:10
  • even i am getting the difference as 0 when i try your snippet. – UserName_Untold Oct 11 '18 at 09:21
  • 1
    No need to roll-your-own solution like this. The modern *java.time* classes can handle this work and do the math. See [this other Answer](https://stackoverflow.com/a/56413601/642706). – Basil Bourque Jun 02 '19 at 11:17
  • how to get seconds? What is the formula? – Prajwal Waingankar Jan 23 '23 at 09:57
7

Note: Corrected code as below which provide by Chirag Raval because in code which Chirag provided had some issues when we try to find time from 22:00 to 07:00.

SimpleDateFormat simpleDateFormat = new SimpleDateFormat("HH:mm");
Date startDate = simpleDateFormat.parse("22:00");
Date endDate = simpleDateFormat.parse("07:00");

long difference = endDate.getTime() - startDate.getTime(); 
if(difference<0)
{
    Date dateMax = simpleDateFormat.parse("24:00");
    Date dateMin = simpleDateFormat.parse("00:00");
    difference=(dateMax.getTime() -startDate.getTime() )+(endDate.getTime()-dateMin.getTime());
}
int days = (int) (difference / (1000*60*60*24));  
int hours = (int) ((difference - (1000*60*60*24*days)) / (1000*60*60)); 
int min = (int) (difference - (1000*60*60*24*days) - (1000*60*60*hours)) / (1000*60);
Log.i("log_tag","Hours: "+hours+", Mins: "+min); 

Result will be: Hours: 9, Mins: 0

Kalpesh
  • 1,767
  • 19
  • 29
4

Have a look at DateFormat, you can use it to parse your strings with the parse(String source) method and the you can easily manipulate the two Dates object to obtain what you want.

DateFormat df = DateFormat.getInstance();
Date date1 = df.parse(string1);
Date date2 = df.parse(string2);
long difference = date1.getTime() - date2.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);

String diffHours = df.format(hours);

For date difference

Date myDate = new Date(difference);

The to show the Date :

String diff = df.format(myDate);
Rahul Baradia
  • 11,802
  • 17
  • 73
  • 121
3

Please try this....

SimpleDateFormat simpleDateFormat = new SimpleDateFormat("HH:mm");

    try {
        date1 = simpleDateFormat.parse("08:00 AM");
    } catch (ParseException e) {
        e.printStackTrace();
    }

    try {
        date2 = simpleDateFormat.parse("04:00 PM");
    } catch (ParseException e) {
        e.printStackTrace();
    }

    long difference = date2.getTime() - date1.getTime();
    int days = (int) (difference / (1000 * 60 * 60 * 24));
    int hours = (int) ((difference - (1000 * 60 * 60 * 24 * days)) / (1000 * 60 * 60));
    int min = (int) (difference - (1000 * 60 * 60 * 24 * days) - (1000 * 60 * 60 * hours))
            / (1000 * 60);
    hours = (hours < 0 ? -hours : hours);
    Log.i("======= Hours", " :: " + hours);
Bill the Lizard
  • 398,270
  • 210
  • 566
  • 880
Sheenzz
  • 59
  • 5
2

I should like to contribute the modern answer.

java.time and ThreeTenABP

    DateTimeFormatter timeFormatter = DateTimeFormatter.ofPattern("hh:mm a", Locale.ENGLISH);

    String startTime = "08:00 AM";
    String endTime = "04:00 PM";

    LocalTime start = LocalTime.parse(startTime, timeFormatter);
    LocalTime end = LocalTime.parse(endTime, timeFormatter);

    Duration diff = Duration.between(start, end);

    long hours = diff.toHours();
    long minutes = diff.minusHours(hours).toMinutes();
    String totalTimeString = String.format("%02d:%02d", hours, minutes);
    System.out.println("TotalTime in Hours and Mins Format is " + totalTimeString);

The output from this snippet is:

TotalTime in Hours and Mins Format is 08:00

(Tested on Java 1.7.0_67 with ThreeTen Backport.)

The datetime classes used in the other answers — SimpleDateFormat, Date, DateFormat and Calendar — are all long outdated and poorly designed. Possibly worse, one answer is parsing and calculating “by hand”, without aid from any library classes. That is complicated and error-prone and never recommended. Instead I am using java.time, the modern Java date and time API. It is so much nicer to work with.

Question: Can I use java.time on Android?

Yes, java.time works nicely on older and newer Android devices. It just requires at least Java 6.

  • In Java 8 and later and on newer Android devices (from API level 26) the modern API comes built-in.
  • In Java 6 and 7 get the ThreeTen Backport, the backport of the modern classes (ThreeTen for JSR 310; see the links at the bottom).
  • On (older) Android use the Android edition of ThreeTen Backport. It’s called ThreeTenABP. And make sure you import the date and time classes from org.threeten.bp with subpackages: org.threeten.bp.Duration, org.threeten.bp.LocalTime and org.threeten.bp.format.DateTimeFormatter.

Links

Ole V.V.
  • 81,772
  • 15
  • 137
  • 161
0
String mStrDifferenceTime =compareTwoTimeAMPM("11:06 PM","05:07 AM");
Log.e("App---Time ", mStrDifferenceTime+" Minutes");

public static String getCurrentDateUsingCalendar() {
    Date mDate = new Date();  // to get the date
    @SuppressLint("SimpleDateFormat") SimpleDateFormat mSimpleDateFormat = new SimpleDateFormat("dd-MM-yyyy"); // getting date in this format
    return mSimpleDateFormat.format(mDate.getTime());
}

public static String getNextDateUsingCalendar() {
    Calendar mCalendar = Calendar.getInstance();
    mCalendar.add(Calendar.DAY_OF_YEAR, 1);
    Date mStrTomorrow = mCalendar.getTime();
    @SuppressLint("SimpleDateFormat") DateFormat mDateFormat = new SimpleDateFormat("dd-MM-yyyy");
    return mDateFormat.format(mStrTomorrow);

}

public static String compareTwoTimeAMPM(String mStrStartTime, String mStrEndTime) {
    String mStrCompareStartTime[] = mStrStartTime.split(" ");
    String mStrCompareEndTime[] = mStrEndTime.split(" ");
    int mIStartTime = Integer.parseInt(mStrCompareStartTime[0].replace(":", ""));
    int mIEndTime = Integer.parseInt(mStrCompareEndTime[0].replace(":", ""));
    String mStrToday = "";
    String mStrTomorrow = "";
    if (mIStartTime < mIEndTime && mStrCompareStartTime[1].equals("PM") && mStrCompareEndTime[1].equals("PM")) {
        mStrToday = getCurrentDateUsingCalendar();
        mStrTomorrow = getCurrentDateUsingCalendar();
    } else if (mIStartTime < mIEndTime && mStrCompareStartTime[1].equals("AM") && mStrCompareEndTime[1].equals("AM")) {
        mStrToday = getCurrentDateUsingCalendar();
        mStrTomorrow = getCurrentDateUsingCalendar();
    } else if (mIStartTime > mIEndTime && mStrCompareStartTime[1].equals("PM") && mStrCompareEndTime[1].equals("PM")) {
        String mStrTime12[] = mStrCompareStartTime[0].split(":");
        if (mStrTime12[0].equals("12")) {
            mStrToday = getNextDateUsingCalendar();
            mStrTomorrow = getNextDateUsingCalendar();
        } else {
            mStrToday = getCurrentDateUsingCalendar();
            mStrTomorrow = getNextDateUsingCalendar();
        }
    } else if (mIStartTime > mIEndTime && mStrCompareStartTime[1].equals("AM") && mStrCompareEndTime[1].equals("AM")) {
        String mStrTime12[] = mStrCompareStartTime[0].split(":");
        if (mStrTime12[0].equals("12")) {
            mStrToday = getNextDateUsingCalendar();
            mStrTomorrow = getNextDateUsingCalendar();
        } else {
            mStrToday = getCurrentDateUsingCalendar();
            mStrTomorrow = getNextDateUsingCalendar();
        }
    } else if (mStrCompareStartTime[1].equals("PM") && mStrCompareEndTime[1].equals("AM")) {
        mStrToday = getCurrentDateUsingCalendar();
        mStrTomorrow = getNextDateUsingCalendar();
    } else if (mStrCompareStartTime[1].equals("AM") && mStrCompareEndTime[1].equals("PM")) {
        mStrToday = getCurrentDateUsingCalendar();
        mStrTomorrow = getCurrentDateUsingCalendar();
    }
    @SuppressLint("SimpleDateFormat") SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd-MM-yyyy hh:mm aa");
    String mStrDifference = "";
    try {
        Date date1 = simpleDateFormat.parse(mStrToday + " " + mStrStartTime);
        Date date2 = simpleDateFormat.parse(mStrTomorrow + " " + mStrEndTime);
        mStrDifference = differenceDatesAndTime(date1, date2);
    } catch (ParseException e) {
        e.printStackTrace();
    }

    return mStrDifference;

}


public static String differenceDatesAndTime(Date mDateStart, Date mDateEnd) {

    long different = mDateEnd.getTime() - mDateStart.getTime();
    long secondsInMilli = 1000;
    long minutesInMilli = secondsInMilli * 60;
    long hoursInMilli = minutesInMilli * 60;
    long daysInMilli = hoursInMilli * 24;

    long elapsedDays = different / daysInMilli;
    different = different % daysInMilli;

    long elapsedHours = different / hoursInMilli;
    different = different % hoursInMilli;

    long elapsedMinutes = different / minutesInMilli;

    long minutes = elapsedHours * 60 + elapsedMinutes;
    long result = elapsedDays * 24 * 60 + minutes;
    if (0 > result) {
        result = result + 720;  //result is minus then add 12*60 minutes
    }

    return result + "";
}

My output is E/App---Time: 361 Minutes

Hitesh sapra
  • 248
  • 2
  • 12
0

You can use extension function in Kotlin like this:

fun Long.toTimeAgo(): String {
    val time = this
    val now = System.currentTimeMillis()

    // convert back to second
    val diff = (now - time) / 1000

    return diff.toString()
}

To get the result in social format, one can modify the code as:

fun Long.toTimeAgo(): String {
    val time = this
    val now = System.currentTimeMillis()

    // convert back to second
    val diff = (now - time) / 1000

    return when {
        diff < MINUTE -> "Just now"
        diff < 2 * MINUTE -> "a minute ago"
        diff < 60 * MINUTE -> "${diff / MINUTE} minutes ago"
        diff < 2 * HOUR -> "an hour ago"
        diff < 24 * HOUR -> "${diff / HOUR} hours ago"
        diff < 2 * DAY -> "a day ago"
        diff < 30 * DAY -> "${diff / DAY} days ago"
        diff < 2 * MONTH -> "a month ago"
        diff < 12 * MONTH -> "${diff / MONTH} months ago"
        diff < 2 * YEAR -> "a year ago"
        else -> "${diff / YEAR} years ago"
    }
}

And now in the code to get the time difference from a date in string, one can use:

    val date = SimpleDateFormat('your date pattern').parse(dateString)
    val timeString = date.time.toTimeAgo()
-4
Try simple piece of code using For 24 hour time
StartTime = "10:00";
EndTime = "13:00";
here starthour=10 and end hour=13 
if(TextUtils.isEmpty(txtDate.getText().toString())||TextUtils.isEmpty(txtDate1.getText().toString())||TextUtils.isEmpty(txtTime.getText().toString())||TextUtils.isEmpty(txtTime1.getText().toString()))
    {
        Toast.makeText(getApplicationContext(), "Date/Time fields cannot be blank", Toast.LENGTH_SHORT).show();
    }
    else {
        if (starthour > endhour) {
            Toast.makeText(getApplicationContext(), "Start Time Should Be Less Than End Time", Toast.LENGTH_SHORT).show();
        } else if (starthour == endhour) {
            if (startmin > endmin) {
                Toast.makeText(getApplicationContext(), "Start Time Should Be Less Than End Time", Toast.LENGTH_SHORT).show();
            }
            else{
                tvalid = "True";
            }
        } else {
            // Toast.makeText(getApplicationContext(),"Sucess"+(endhour-starthour)+(endmin-startmin),Toast.LENGTH_SHORT).show();
            tvalid = "True";
        }
    }
same for date also
Syed Danish Haider
  • 1,334
  • 11
  • 15