【发布时间】:2013-02-26 01:10:53
【问题描述】:
我有以下代码,通常需要一些时间实例,将它们转换为毫秒以进行一些相当精确的计算,并在这些时间之间产生等效的天数或它们之间的小时数(视情况而定)是。我认为代码最能解释我想要实现的目标。以下是一些sn-ps...
private int hours = 0;
/* This is intended to get the days between 'startDate' and 'endDate'
* and ensure it is between zero & the specified 'range' of days, inclusive*/
public int getPeriodBtw(Date startDate, Date endDate, int range)
{
int daysBtw = 0;
Calendar constantDate = Calendar.getInstance();
constantDate.setTime(startDate);
Calendar currentDate = Calendar.getInstance();
currentDate.setTime(endDate);
long rangePeriod = Period.ConvertDaysToMillis(range);
long duration = (constantDate.getTimeInMillis() + rangePeriod) - currentDate.getTimeInMillis();
daysBtw = (int)Period.ConvertMillisToDays(duration);
if(duration >= 0 && duration <= rangePeriod)
{
if(daysBtw == 0){
hours = (int)Period.ConvertMillisToHours(duration);
}
}
return daysBtw;
}
现在,上面的逻辑对我来说似乎很紧密而且很好,但令人惊讶的是,随着currentDate 的变化,我得到了奇怪的结果。我的意思是,通常我会期待这样的事情......见下图;
如果constantDate = 10:00am
如果range = 1 day从constantDate开始
让我们在同一天说currentDate = 2:00pm(即在range内),
那么daysBtw 应该返回 = 0constantDate 和 currentDate 之间的小时数是 4hrs
现在这意味着currentDate 是 4hrs 减去range,
因此duration 应该是1day(24hrs) - 4hrs = 20hrs
当然,我认为在从纪元开始的毫秒偏移中处理这个是这样的;
10:00am(millis) + 1day(millis) - 2:00pm(millis) = 20hrs
long duration = (constantDate.getTimeInMillis() + rangePeriod) - currentDate.getTimeInMillis();
hours = (int)Period.ConvertMillisToHours(duration);
所以hours 应该返回 = 20
现在,如果currentDate 更改为3:00pm,按照前面描述的相同逻辑,不应该hours = 19???...问题是,我的程序得到了hours = 21。
我真的很困惑我可能做错了什么。是我的逻辑有问题吗???...或者它在我的代码中的某个地方???...承认我已经花了几个小时断断续续地做这件事,我知道这很简单,我感到非常糟糕,但是时间不像往常一样是我的朋友,我必须继续做一些不那么琐碎的事情。任何形式的帮助将不胜感激。谢谢大家!
【问题讨论】:
-
要筛选的代码很多。你能把它减少到一个 10 行的 test-case 来证明这个问题吗?
-
为什么有这么多反对票?
-
@Oli Charlesworth,感谢您让我知道我是如何站在人们的错误一边的。是否试图避免以后被要求提供更多代码。我在不破坏其本质的情况下尽可能地减少了代码......我仍然期待解决方案......谢谢!
-
@Sednus 我觉得他们都想教我如何正确使用 S-O。幸好我明白了……你对我的问题有什么帮助吗?会很高兴。
标签: java date time business-logic