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!
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.
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.
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.
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
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With