7

I am developing and android app, where I need to calculate the difference between two times.I need to calculate the time difference for 24 hrs, and also the difference between times on two days(Eg. 5pm today to 9 am tomorrow).

I have tried the below code, to calculate the difference which works only for 24 hrs,

String dateStart = "08:00:00";
String dateStop = "13:00:00";

//HH converts hour in 24 hours format (0-23), day calculation
SimpleDateFormat format = new SimpleDateFormat("HH:mm:ss");

Date d1 = null;
Date d2 = null;

try 
{
    d1 = format.parse(dateStart);
    d2 = format.parse(dateStop);

    //in milliseconds
    long diff = d2.getTime() - d1.getTime();
    long diffHours = diff / (60 * 60 * 1000) % 24;
    Log.e("test",diffHours + " hours, ");
}
catch (Exception e) 
{
    // TODO: handle exception
} 
Ryan Haining
  • 35,360
  • 15
  • 114
  • 174
Dave
  • 297
  • 3
  • 4
  • 15
  • Check [this](http://stackoverflow.com/questions/5172593/how-to-calculate-the-time-difference-between-two-time-fields-with-respect-to-t/11219953#11219953). Hope it helps. – Hardik Joshi Sep 20 '13 at 04:29

6 Answers6

13

Sir, you can make it easily in using java feature. long difference = date2.getTime() - date1.getTime(); Take a look in this link this will help you.

Pradip
  • 3,189
  • 3
  • 22
  • 27
  • I have tried this link, but I am not supplying date along with the input, I need to get the time difference using only the time. I can supply am or pm values. – Dave Sep 20 '13 at 05:04
  • ok, In background set the date and pass it. As you are passing the am/pm from it you can update the second time's date to tomorrow/today. Have you got my point. – Pradip Sep 20 '13 at 05:11
10

Correct way to find proper time difference:

SimpleDateFormat simpleDateFormat = new SimpleDateFormat("HH:mm:ss");
Date startDate = simpleDateFormat.parse("22:00:59");
Date endDate = simpleDateFormat.parse("23:00:10");

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

Result will be: Hours: 0, Mins: 59, Secs: 11

Kalpesh
  • 1,767
  • 19
  • 29
7

tl;dr

ChronoUnit.HOURS.between( 
    LocalTime.parse( "08:00:00" ) , 
    LocalTime.parse( "13:00:00" ) 
)

5

…or…

ChronoUnit.HOURS.between( 
    ZonedDateTime.of( 
        LocalDate.of( 2017 , Month.JANUARY , 23 ) ,
        LocalTime.parse( "08:00:00" ) , 
        ZoneId.of( "America/Montreal" )
    ) , 
    ZonedDateTime.of( 
        LocalDate.of( 2017 , Month.JANUARY , 25 ) ,
        LocalTime.parse( "13:00:00" ) , 
        ZoneId.of( "America/Montreal" )
    ) 
) 

53

java.time

Modern approach uses the java.time classes.

LocalTime

The LocalTime class represents a time-of-day without a date and without a time zone.

LocalTime start = LocalTime.parse( "08:00:00" ) ;
LocalTime stop = LocalTime.parse( "13:00:00" ) ;

Duration

Get a Duration object to represent the span-of-time.

Duration d = Duration.between( start , stop ) ;

ChronoUnit

For number of hours, use ChronoUnit.

long hours = ChronoUnit.HOURS.between( start , stop ) ;

Android

For Android, see the ThreeTen-Backport and ThreeTenABP projects. See last bullets below.

ZonedDateTime

If you want to cross days, going past midnight, you must assign dates and time zones.

A time zone is crucial in determining a date. For any given moment, the date varies around the globe by zone. For example, a few minutes after midnight in Paris France is a new day while still “yesterday” in Montréal Québec.

Specify a proper time zone name in the format of continent/region, such as America/Montreal, Africa/Casablanca, or Pacific/Auckland. Never use the 3-4 letter abbreviation such as EST or IST as they are not true time zones, not standardized, and not even unique(!).

ZoneId z = ZoneId.of( "America/Montreal" ) ;

ZonedDateTime start = ZonedDateTime.of( 
    LocalDate.of( 2017 , Month.JANUARY , 23 ) ,
    LocalTime.parse( "08:00:00" ) , 
    z
) ;

ZonedDateTime stop = ZonedDateTime.of( 
    LocalDate.of( 2017 , Month.JANUARY , 25 ) ,
    LocalTime.parse( "13:00:00" ) , 
    z
) ;

long hours = ChronoUnit.HOURS.between( start , stop ) ;

See this code run live at IdeOne.com.

53


About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

Where to obtain the java.time classes?

Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
2

You can try something like this also if you are sure the 9 am is next day you can add one day and calculate the difference:

String string1 = "05:00:00 PM";
    Date time1 = new SimpleDateFormat("HH:mm:ss aa").parse(string1);
    Calendar calendar1 = Calendar.getInstance();
    calendar1.setTime(time1);

    String string2 = "09:00:00 AM";
    Date time2 = new SimpleDateFormat("HH:mm:ss aa").parse(string2);
    Calendar calendar2 = Calendar.getInstance();
    calendar2.setTime(time2);
    calendar2.add(Calendar.DATE, 1);

    Date x = calendar1.getTime();
    Date xy = calendar2.getTime();
    long diff = x.getTime() - xy.getTime();
    diffMinutes = diff / (60 * 1000);
    float diffHours = diffMinutes / 60;
    System.out.println("diff hours" + diffHours);
Srikanth Roopa
  • 1,782
  • 2
  • 13
  • 19
0
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
-2

I worked it out this way:

Date time1 = new SimpleDateFormat("HH:mm:ss aa").parse(string1);
Calendar calendar1 = Calendar.getInstance();
calendar1.setTime(time1);

Date time2 = new SimpleDateFormat("HH:mm:ss aa").parse(string2);
Calendar calendar2 = Calendar.getInstance();
calendar2.setTime(time2);

if(calendar2.get(Calendar.AM_PM) == 1 && calendar1.get(Calendar.AM_PM) == 0)     {
     calendar2.add(Calendar.DATE, 1);
}
long diff = calendar1.getTimeInMillis() - calendar2.getTimeInMillis()

This will help to find the difference in time round the clock.

user_1989
  • 375
  • 4
  • 10