What's a good method to, given two Date objects, compare the difference between their time portion only, completely ignoring Year, Month and Day?
It's quite the opposite of this question.
UPDATE: Here's the final code for future reference:
private long differenceBetween(Date currentTime, Date timeToRun) { Calendar currentCal = Calendar.getInstance(); currentCal.setTime(currentTime); Calendar runCal = Calendar.getInstance(); runCal.setTime(timeToRun); runCal.set(Calendar.DAY_OF_MONTH, currentCal.get(Calendar.DAY_OF_MONTH)); runCal.set(Calendar.MONTH, currentCal.get(Calendar.MONTH)); runCal.set(Calendar.YEAR, currentCal.get(Calendar.YEAR)); return currentCal.getTimeInMillis() - runCal.getTimeInMillis(); }
I am afraid there is no method of comparing two dates that could be called "easy" or "simple". When comparing two time instances with any sort of reduced precision (e.g. just comparing dates), you must always take into account how time zone affects the comparison.
To compare dates in MySQL except time portion of a datetime field, you can use DATE () function. The syntax is as follows − To understand the above concept, let us create a table.
If you strictly want to use Date ( java.util.Date ), or without any use of external Library. Use this : Show activity on this post. I am simply setting hours/minutes/second to 0 so no issue with the time as time will be same now for both dates. now you simply use compareTo.
The diff value represents the number of days for the age. If the value is negative the start date falls after the end date. This is a good check. Show activity on this post. You can use Equals or CompareTo. Equals: Returns a value indicating whether two DateTime instances have the same date and time value.
If you want to compare the underlying binary (long int) values of the dates, you can do this:
public int compareTimes(Date d1, Date d2) { int t1; int t2; t1 = (int) (d1.getTime() % (24*60*60*1000L)); t2 = (int) (d2.getTime() % (24*60*60*1000L)); return (t1 - t2); }
Addendum 1
This technique has the advantage of speed, because it uses the underlying long
value of the Date
objects directly, instead of converting between ticks and calendar components (which is rather expensive and slow). It's also a lot simpler than messing with Calendar
objects.
Addendum 2
The code above returns the time difference as an int
, which will be correct for any pair of times, since it ignores the year/month/day portions of the dates entirely, and the difference between any two times is no more than 86,400,000 ms (= 1000 ms/sec × 60 sec/min × 60 min/hr × 24 hr/day).
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