I have two dates:
toDate
(user input in MM/dd/yyyy
format)currentDate
(obtained by new Date()
) I need to compare the currentDate
with toDate
. I have to display a report only when the toDate
is equal to or more than currentDate
. How can I do that?
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.
Core Java The class Date represents a specific instant in time, with millisecond precision. To find out if two Date objects contain the same day, we need to check if the Year-Month-Day is the same for both objects and discard the time aspect.
The after() method is used to check if a given date is after another given date. Return Value: true if and only if the instant represented by this Date object is strictly later than the instant represented by when; false otherwise.
It is easier to compare dates using the java.util.Calendar
. Here is what you might do:
Calendar toDate = Calendar.getInstance(); Calendar nowDate = Calendar.getInstance(); toDate.set(<set-year>,<set-month>,<set-day>); if(!toDate.before(nowDate)) { //display your report } else { // don't display the report }
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