Calculate difference between two times android
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:
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
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.
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….
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:
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);
Dave
Updated on September 04, 2020Comments
-
Dave over 3 years
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 }
-
Dave over 10 yearsI 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.
-
Pradip over 10 yearsok, 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.
-
Ravi Bhandari about 9 yearsnice answer,help me alot :)
-
SKG over 5 yearsAwesome! I really like how you dealt with changing date
-
Naveen almost 4 yearsHi, How to get Seconds in the same format like hours, min ?
-
Kalpesh over 3 years@Naveen Sorry for bit late, I updated answer above for calculate seconds too, hope this help you and others too.
-
Mahmoud Ayman about 3 yearsitsn't working when i try it with from
13:00 PM
to11:00 AM
-
Mahmoud Ayman about 3 yearsAWESOME, this should be the accepted answer
-
Shriraksha bhat about 2 yearsAwesome! this resolved my issue