NFE NFE - 2 months ago 16
Java Question

How to get hour/minute difference in java

I have to get total minutes between two hour.

17:00 and 16.06 hrs


If I do like

17.00-16.06 =0.94


but correct answer is 54 minutes.

so logically how can I get difference minutes from two time.

without using Calender api or Joda Time.

Code:

private double getTimeDifference(Date startDate,Date endDate, boolean sameDay)
{
double startTimeF=Double.valueOf(startDate.getHours()+"."+startDate.getMinutes());
double endTimeF=Double.valueOf(endDate.getHours()+"."+endDate.getMinutes());
double totalTime=0;
boolean isCalculated=false;
for(double workTime:timeMap.keySet())
{
double endTimeC=timeMap.get(workTime);

if(startTimeF>=workTime && startTimeF<=endTimeC)
{
if(endTimeF<endTimeC && sameDay)
{
isCalculated=true;
totalTime+=endTimeF-startTimeF;
}
else
{
totalTime+=endTimeC-startTimeF;
}
break;
}
}

for(double workTime:timeMap.keySet())
{
double endTimeC=timeMap.get(workTime);
if(endTimeF>=workTime && endTimeF<=endTimeC)
{
if(!isCalculated)
{
if(workTime<startTimeF && sameDay)
{
totalTime+=endTimeF-startTimeF;
}
else
{
totalTime+=endTimeF-workTime;
}
}

}
else if(!sameDay)
{
totalTime+=endTimeC-workTime;
}
}
return totalTime;
}


Time map contains key and value of json string:


{"time":[{"startTime":"8:00", "endTime":"12:30", "type":"Working"},{"startTime":"12:31", "endTime":"13:00", "type":"Break"},{"startTime":"13:01", "endTime":"17:00", "type":"Working"}]}

Answer
long milliDifference = date1.getTime() - date2.getTime();
long minuteDifference = TimeUnit.MINUTES.convert(milliDifference, TimeUnit.MILLISECONDS);

where date1 and date2 are of type java.util.Date.