Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 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
} 
like image 709
Dave Avatar asked Sep 20 '13 04:09

Dave


People also ask

How do you find the difference in time between two times?

Calculate the duration between two times First, identify the starting and an ending time. The goal is to subtract the starting time from the ending time under the correct conditions. If the times are not already in 24-hour time, convert them to 24-hour time. AM hours are the same in both 12-hour and 24-hour time.

How can I get the difference between two dates in Android?

long currentTime = System. currentTimeMillis(); long previousTime = (System. currentTimeMillis() - 864000000); //10 days ago Log. d("DateTime: ", "Difference With Second: " + AppUtility.

How do you find the difference between two times manually?

Compute time difference manuallySubtract all end times from hours to minutes. If the start minutes is higher than the end minutes, subtract an hour from the end time hours and add 60 minutes to the end minutes. Proceed to subtract the start time minutes to the end minutes. Subtract the hours too from end to start.

How does kotlin calculate date difference?

long diff = date1. getTime() - date2. getTime(); Date diffDate = new Date(diff);


4 Answers

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.

like image 159
Pradip Avatar answered Nov 03 '22 01:11

Pradip


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

like image 26
Kalpesh Avatar answered Nov 02 '22 23:11

Kalpesh


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?

  • Java SE 8, Java SE 9, and later
    • Built-in.
    • Part of the standard Java API with a bundled implementation.
    • Java 9 adds some minor features and fixes.
  • Java SE 6 and Java SE 7
    • Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
  • Android
    • The ThreeTenABP project adapts ThreeTen-Backport (mentioned above) for Android specifically.
    • See How to use ThreeTenABP….
like image 41
Basil Bourque Avatar answered Nov 03 '22 01:11

Basil Bourque


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);
like image 40
Srikanth Roopa Avatar answered Nov 03 '22 01:11

Srikanth Roopa