Should I use Calendar.compareTo() to compare dates?
Date implements comparable itself so there's no reason to wrap it into calendar:
Calendar someCalendar1 = Calendar.getInstance(); // current date/time
someCalendar1.add(Calendar.DATE, -14);
if (someDate.compareTo(someCalendar1.getTime()) < 0) {
...Code...
}
Date also has convenient after() and before() methods that make the above comparison easier to read:
if (someDate.before(someCalendar1.getTime())) {
...Code...
}
Finally, if you're dealing with date / time a lot, do consider using Joda Time instead of built-in java classes. It's MUCH more convenient and functional:
DateTime dt = new DateTime().minusWeeks(2);
if (new DateTime(someDate).isBefore(dt)) {
...Code...
}
It's valid, but you're slightly confused about someDate
- Calendar.setTime
takes a java.util.Date
, which is just a wrapper around a long
indicating the number of milliseconds since midnight Jan 1st 1970, UTC. It's not "in the format MM/dd/yyy" - that's a string representation, not a java.util.Date
. If it happens to print something out in the format MM/dd/yyyy
, that's just what Date.toString
is doing for you - it's not inherently part of the format.
As an aside, I would personally recommend that you avoid java.util.Date
and java.util.Calendar
completely and use Joda Time instead. It's a much better API.