Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Date only comparison using "isBefore" in Java Joda Time

Is there a way to have only dates compared for DateTime object with isBefore function?

For ex.,

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

Now when I do,

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

This results in inconsistent behavior (for my scenario) as it is taking into consideration time as well whereas what I want is to have just the dates compared using isBefore. Is there a way I can do that?

Please let me know.

Thanks!

like image 502
test123 Avatar asked Mar 07 '12 21:03

test123


People also ask

How do you compare only the date and not time?

Fortunately you can use the INT() function in Excel to extract just the date from a datetime value, which allows you to easily compare dates while ignoring the time.

How can I compare two date and time in Java?

In Java, two dates can be compared using the compareTo() method of Comparable interface. This method returns '0' if both the dates are equal, it returns a value "greater than 0" if date1 is after date2 and it returns a value "less than 0" if date1 is before date2.

How does Java Util date compare without time?

If you want to compare just the date part without considering time, you need to use DateFormat class to format the date into some format and then compare their String value. Alternatively, you can use joda-time which provides a class LocalDate, which represents a Date without time, similar to Java 8's LocalDate class.


2 Answers

If you want to compare dates only you probably want to use the LocalDate class, rather than a DateTime.

The JodaTime docs are pretty good: http://joda-time.sourceforge.net/apidocs/org/joda/time/LocalDate.html

like image 55
Tim Gage Avatar answered Oct 24 '22 08:10

Tim Gage


Another strategy is to format it.

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);
}    
like image 45
FAtBalloon Avatar answered Oct 24 '22 08:10

FAtBalloon