Skip to content Skip to sidebar Skip to footer

Calculate Difference Between Two Times Android

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 time

Solution 1:

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.

Solution 2:

Correct way to find proper time difference:

SimpleDateFormatsimpleDateFormat=newSimpleDateFormat("HH:mm:ss");
DatestartDate= simpleDateFormat.parse("22:00:59");
DateendDate= simpleDateFormat.parse("23:00:10");

longdifference= endDate.getTime() - startDate.getTime(); 
if(difference<0)
{
    DatedateMax= simpleDateFormat.parse("24:00:00");
    DatedateMin= simpleDateFormat.parse("00:00:00");
    difference=(dateMax.getTime() -startDate.getTime() )+(endDate.getTime()-dateMin.getTime());
}
intdays= (int) (difference / (1000*60*60*24));  
inthours= (int) ((difference - (1000*60*60*24*days)) / (1000*60*60)); 
intmin= (int) (difference - (1000*60*60*24*days) - (1000*60*60*hours)) / (1000*60);
intsec= (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

Solution 3:

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.

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

Duration

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

Durationd= 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(!).

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

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

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

longhours= 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?

Solution 4:

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:

Stringstring1="05:00:00 PM";
    Datetime1=newSimpleDateFormat("HH:mm:ss aa").parse(string1);
    Calendarcalendar1= Calendar.getInstance();
    calendar1.setTime(time1);

    Stringstring2="09:00:00 AM";
    Datetime2=newSimpleDateFormat("HH:mm:ss aa").parse(string2);
    Calendarcalendar2= Calendar.getInstance();
    calendar2.setTime(time2);
    calendar2.add(Calendar.DATE, 1);

    Datex= calendar1.getTime();
    Datexy= calendar2.getTime();
    longdiff= x.getTime() - xy.getTime();
    diffMinutes = diff / (60 * 1000);
    floatdiffHours= diffMinutes / 60;
    System.out.println("diff hours" + diffHours);

Solution 5:

Try simple piece of code using For 24 hour time
StartTime = "10:00";
EndTime = "13:00";
here starthour=10andend hour=13if(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();
        } elseif (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 fordate also

Post a Comment for "Calculate Difference Between Two Times Android"