Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if one date is exactly 24 hours or more after another

Tags:

java

date

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?

like image 458
Zach Sugano Avatar asked Jun 21 '12 20:06

Zach Sugano


People also ask

How can I compare two dates?

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.

How do you check if a date exists between two dates?

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.


2 Answers

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
like image 188
Ted Hopp Avatar answered Oct 16 '22 20:10

Ted Hopp


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.

like image 30
Pshemo Avatar answered Oct 16 '22 18:10

Pshemo