I'm trying to calculate the difference between 2 times. It works well, unless the two dates are on each side of midnight. In that case I get a negative answer. Any ideas how I can improve the code to fix this issue?
String sleepStart = editFallAsleepTime.getText().toString();
String sleepStop = editWakeUpTime.getText().toString();
String awakeTimeString = ((Globals) getActivity().getApplication()).getAwakeTime();
//HH converts hour in 24 hours format (0-23), day calculation
SimpleDateFormat format = new SimpleDateFormat("HH:mm");
Date d1 = null;
Date d2 = null;
try
{
d1 = format.parse(sleepStart);
d2 = format.parse(sleepStop);
float t1 = d1.getTime();
float t2 = d2.getTime();
if( t2 <= t1 ){
t2 +=24;
}
float diff = t2 - t1;
//in milliseconds
float diff = d2.getTime() - d1.getTime();
float diffHours = diff / (60 * 60 * 1000);
float awakeTime = Float.valueOf(awakeTimeString);
float awakeHours = awakeTime / 60;
float calcEffectiveSleep = diffHours - awakeHours;
String sleepTime = Float.toString(diffHours);
String effectiveSleep = Float.toString(calcEffectiveSleep);
((Globals) getActivity().getApplication()).setEffectiveSleep(effectiveSleep);
}
catch (Exception e)
{
Log.e("timediff","didntwork");
}