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
}
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.
long currentTime = System. currentTimeMillis(); long previousTime = (System. currentTimeMillis() - 864000000); //10 days ago Log. d("DateTime: ", "Difference With Second: " + AppUtility.
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.
long diff = date1. getTime() - date2. getTime(); Date diffDate = new Date(diff);
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.
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
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
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 ) ;
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
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?
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With