I am using the compareTo method in Java to try and check if a certain date is greater than or equal than 24 hours after another date.
How do I determine what integer to compare the date to?
For comparing the two dates, we have used the compareTo() method. If both dates are equal it prints Both dates are equal. If date1 is greater than date2, it prints Date 1 comes after Date 2. If date1 is smaller than date2, it prints Date 1 comes after Date 2.
To check if a date is between two dates: Use the Date() constructor to convert the dates to Date objects. Check if the date is greater than the start date and less than the end date. If both conditions are met, the date is between the two dates.
Use the Calendar
class. If you already have a Date
object, you can still use Calendar
:
Date aDate = . . .
Calendar today = Calendar.getInstance();
today.setTime(aDate);
Calendar tomorrow = Calendar.getInstance();
tomorrow.setTime(aDate);
tomorrow.add(Calendar.DAY, 1);
Date tomorrowDate = tomorrow.getTime(); // if you need a Date object
Answer depends on what you want to achieve.
One way, could be checking difference in milliseconds. 24 h in milliseconds can be calculated via
24 * 60 * 60 * 1000 = 86400000
h min sec millis
(in code you can also write TimeUnit.HOURS.toMillis(24)
which IMO is more readable)
So now you can just check if difference between two dates (expressed in milliseconds) is greater than 86400000.
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