2012-03-07 35 views
13

有没有办法只有日期对比DateTime object with isBefore函数?仅在Java Joda时间使用“isBefore”进行日期比较

对于离,

DateTime start = new DateTime(Long.parseLong(<someInput>)); 
DateTime end = new DateTime(Long.parseLong(<someInput>)); 

现在,当我这样做,

while (start.isBefore(end)) { 
    // add start date to the list 
    start = start.plusDays(1); 
} 

这导致不一致的行为(我的情况),因为它是考虑到时间以及而我想要的是使用isBefore比较日期。有没有办法可以做到这一点?

请让我知道。

谢谢!

回答

21

如果您只想比较日期,则可能需要使用LocalDate类,而不是DateTime

的JodaTime文档都还不错:http://joda-time.sourceforge.net/apidocs/org/joda/time/LocalDate.html

+0

感谢您的回复。我想将DateTime存储在循环中,所以不用将DateTime转换为LocalDate,然后将LocalDate转换回DateTime,我认为使用DateFormatter更好。 – test123 2012-03-07 22:10:33

+1

只需确保您在进入/离开夏令时时不会有任何奇怪的行为!日期和时间往往比第一次出现时更复杂...... – 2012-03-07 22:16:24

+1

我刚刚重新评估了我的应用程序的用例,并且看起来像使用LocalDate会更好。谢谢! – test123 2012-03-07 22:18:41

1

切换到使用LocalDate而不是DateTime。 JodaTime中的概念是“部分”(请参阅​​ReadablePartial界面)。

+0

感谢您的回复。我只想将日期时间格式存储在循环中。所以我认为我会坚持乔治在下面提出的建议。谢谢! – test123 2012-03-07 22:08:33

0

您可以设置解析后DateTime为零(这意味着午夜)时间:

// withTime sets hours, minutes, seconds, milliseconds 
DateTime start = new DateTime(Long.parseLong(<someInput>)).withTime(0, 0, 0, 0); 
DateTime end = new DateTime(Long.parseLong(<someInput>)).withTime(0, 0, 0, 0); 

或者使用其他约达时间的一个类;还有比DateTime更多的!如果您只处理日期,则可能需要使用LocalDate而不是DateTime

+0

感谢您的回复!仔细查看我的应用程序后,我想我会将其更改为LocalDate而不是DateTime。谢谢! – test123 2012-03-07 22:18:01

+2

如果时区具有包括午夜在内的夏令时间差,则将时间设置为午夜将不起作用。调用'dayOfMonth()。roundFloorCopy()'处理边缘情况。 – JodaStephen 2012-04-19 10:09:21

8

另一种策略是对其进行格式化。

DateFormat df = new SimpleDateFormat("MM/dd/yyyy"); 
DateTime newStart = df.parse(start); 
DateTime newEnd = df.parse(end); 

while (newStart.isBefore(newEnd)) { 
    // add start date to the list 
    newStart = newStart.plusDays(1); 
}  
+0

这是最接近我想要的。非常感谢您的建议! – test123 2012-03-07 22:06:15

+0

df.parse不接受DateTime :-( – test123 2012-03-07 22:14:12

+0

尝试df.parse(start.toString()); – JCab 2012-03-07 22:17:06