我有以下代码,通常会需要一些时间的实例,将它们转换为毫秒来做出一些相当精确的计算,并且在这些时间之间或者小时之间产生相等的日期(视情况而定) 。我认为代码最能解释我正在努力实现的目标。以下是一些片断......Millis中的时间计算没有产生预期结果。有人可以帮助说明原因吗?
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
IE),
然后daysBtw
应该返回constantDate
和currentDate
之间= 0
小时4hrs
现在这意味着currentDate
是4hrs
减去range
,
因此duration
应该1day(24hrs) - 4hrs = 20hrs
当然我觉得这个处理在毫秒从时代偏移WLD是像这样;
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行[测试用例](http:// sscce。组织)这证明了这个问题? – 2013-03-10 23:01:18
为什么这么多downvotes? – Sednus 2013-03-10 23:19:15
@奥利查尔斯沃思,谢谢你让我知道我是如何陷在人们的错误的一面。 tryna避免在稍后被要求更多代码。我尽可能地减少了代码,而不会改变它的本质......我仍然期待着解决方案tho ... Thanx! – CodeBurner 2013-03-11 00:10:10