Calculate the difference between two-time android

I am developing an android application where I need to calculate the difference between two points. I need to calculate the time difference within 24 hours, as well as the difference between the times for two days (for example, from 5 p.m. to 9 a.m. tomorrow).

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

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 } 
+7
java android date time simpledateformat
source share
6 answers

Sir, you can easily use the java function. long difference = date2.getTime() - date1.getTime(); Look at this link , it will help you.

+13
source share

The correct way to determine the time difference:

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

The result will be: Hours: 9, Min .: 0

+3
source share

You can also try something like this if you are sure that at 9 a.m. the 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); 
+2
source share

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

The modern approach uses the java.time classes.

LocalTime

LocalTime class is a time of day with no date and no time zone.

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

Duration

Get a Duration object to display the time span.

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

ChronoUnit

For the number of hours use ChronoUnit .

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

Android

For Android, see the ThreeTen-Backport and ThreeTenABP projects. See the latest ammo below.

ZonedDateTime

If you want to cross days after midnight, you must set dates and time zones.

The time zone is critical for determining the date. At any given moment, the date changes around the world by zone. For example, a few minutes after midnight in Paris, France is a new day, still "yesterday" in Montreal Quebec .

Specify the time zone name in continent/region format, such as America/Montreal , Africa/Casablanca or Pacific/Auckland . Never use the abbreviation 3-4 letters, for example, EST or IST , since they are not real time zones, and are not standardized or 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 on IdeOne.com .

53


About java.time

The java.time framework is built into Java 8 and later. These classes supersede the nasty old legacy time classes such as java.util.Date , Calendar and SimpleDateFormat .

The Joda-Time project, now in maintenance mode , we recommend switching to the java.time classes.

To learn more, see the Oracle Tutorial . And search for qaru for many examples and explanations. JSR 310 specification .

Where to get java.time classes?

  • Java SE 8 , Java SE 9 , and then
    • Built in.
    • Part of the standard Java API with integrated implementation.
    • Java 9 adds some minor features and fixes.
  • Java SE 6 and Java SE 7
  • Android
    • The ThreeTenABP project adapts ThreeTen-Backport (mentioned above) specifically for Android.
    • See How to use ThreeTenABP ....
+2
source share

I worked like this:

 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 you find the time difference between the clocks.

0
source share
 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 
0
source share

All Articles