我试图计算2次之间的差异。 它运作良好,除非两个日期在午夜的每一边。 在那种情况下,我得到一个否定的答案。 我有什么想法可以改进代码来解决这个问题吗?
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");
}
答案 0 :(得分:1)
如果您在1天间隔内的差异,那么您可以考虑处理d2&lt; d1案例正如@Andre Classen所说。怎么做是:
t1 = d1.getTime();
t2 = d2.getTime();
if( t2 <= t1 ){
t2 +=24*60*60*1000;
}
diff = t2 - t1;