Compare only the time portion of two dates, ignoring the date part

38,054

Solution 1

tl;dr

Duration                                  // Span of time, with resolution of nanoseconds.
.between(                                 // Calculate elapsed time.
    LocalTime.now(                        // Get current time-of-day…
        ZoneId.of( "Pacific/Auckland" )   // … as seen in a particular time zone.
    )                                     // Returns a `LocalTime` object.
    ,
    myJavaUtilDate                        // Avoid terrible legacy date-time classes such as `java.util.Date`.
    .toInstant()                          // Convert from `java.util.Date` to `java.time.Instant`, both representing a moment in UTC.
    .atZone(                              // Adjust from UTC to a particular time zone. Same moment, same point on the timeline, different wall-clock time.
        ZoneId.of( "Pacific/Auckland" )   // Specify time zone by proper naming in `Continent/Region` format, never 2-4 letter pseudo-zones such as `PST`, `CEST`, `CST`, `IST`, etc.
    )                                     // Returns a `ZonedDateTime` object.
    .toLocalTime()                        // Extract the time-of-day without the date and without a time zone.
)                                         // Returns a `Duration` object.
.toMillis()                               // Calculate entire span-of-time in milliseconds. Beware of data-loss as `Instant` uses a finer resolution the milliseconds, and may carry microseconds or nanoseconds.

I suggest passing around the type-safe and self-explanatory Duration object rather than a mere integer number of milliseconds.

java.time

The modern approach uses the java.time classes that supplanted the terrible legacy classes such as Date, Calendar, SimpleDateFormat.

Table of all date-time types in Java, both modern and legacy

Convert your java.util.Date (a moment in UTC), to an Instant. Use new conversion methods added to the old classes.

Instant instant = myJavaUtilDate.toInstant() ;

That represents a moment in UTC. Determining a date and a time-of-day requires a time zone . For any given moment, the date and time vary around the globe by zone. For example, a few minutes after midnight in Paris France is a new day while still “yesterday” in Montréal Québec.

If no time zone is specified, the JVM implicitly applies its current default time zone. That default may change at any moment during runtime(!), so your results may vary. Better to specify your desired/expected time zone explicitly as an argument.

Specify a proper time zone name in the format of continent/region, such as America/Montreal, Africa/Casablanca, or Pacific/Auckland. Never use the 2-4 letter abbreviation such as EST or IST as they are not true time zones, not standardized, and not even unique(!).

ZoneId z = ZoneId.of( "America/Montreal" ) ;  

If you want to use the JVM’s current default time zone, ask for it and pass as an argument. If omitted, the JVM’s current default is applied implicitly. Better to be explicit, as the default may be changed at any moment during runtime by any code in any thread of any app within the JVM.

ZoneId z = ZoneId.systemDefault() ;  // Get JVM’s current default time zone.

Assign the ZoneId to the Instant to produce a ZonedDateTime object.

ZonedDateTime zdt = instant.atZone( z ) ;

Extract the time-of-day portion, without the date and without the time zone.

LocalTime lt = zdt.toLocalTime() ;

Compare. Calculate elapsed time with a Duration.

Duration d = Duration.between( ltStart , ltStop ) ;

Be aware that this is not a fair comparison. Days are not always 24-hours long, and not all time-of-day values are valid on all days in all zones. For example, in the United States during a Daylight Saving Time cutover, there may not be a 2 AM hour at all. So 1 AM to 4 AM may be 3 hours on one date but only 2 hours on another date.


About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.

Where to obtain the java.time classes?

Table of which java.time library to use with which version of Java or Android

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

Solution 2

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).

Solution 3

You may consider using Joda time's DateTimeComparator.getTimeOnlyInstance() for a comparator that will compare two Joda dates based only upon the times.

For example:

DateTimeComparator comparator = DateTimeComparator.getTimeOnlyInstance();
comparator.compare(date1, date2);

See http://joda-time.sourceforge.net/api-release/org/joda/time/DateTimeComparator.html#getTimeOnlyInstance()

Solution 4

Take a look at the Calendar class. It has support for extracting hours, minutes, and seconds from given Date's.

Calendar calendar = Calendar.getInstance();
calendar.setTime(yourDateObject);
int hour = calendar.get(Calendar.HOUR);
int minute = calendar.get(Calendar.MINUTE);
int second = calendar.get(Calendar.SECOND);

Solution 5

In case you can't use JODA,

create 2 calendar objects, set year, month and day to 0.

Compare them....

Share:
38,054
Jay El-Kaake
Author by

Jay El-Kaake

Updated on October 16, 2020

Comments

  • Jay El-Kaake
    Jay El-Kaake over 3 years

    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();
    }
    
  • bbaja42
    bbaja42 over 12 years
    If (java) time is the question, JODA is the answer :D
  • scottb
    scottb about 11 years
    This is the best answer, imo. There is no need to use a complex Calendar API to compare time values within Date objects.
  • Pi Horse
    Pi Horse about 9 years
    this is perfect and smart
  • Beep.exe
    Beep.exe almost 9 years
    thnx david, exactly what i was looking for :)
  • richardaum
    richardaum over 8 years
    Very nice! Gooooooood!
  • confile
    confile over 8 years
    This does not always work. Example: currentDate: Tue Oct 20 16:28:57 MESZ 2015 and validFromTime: Tue Oct 20 01:30:00 MESZ 2015 returns the wrong result.
  • Stefan Falk
    Stefan Falk about 8 years
    @bbaja42 Not is you use GWT :/
  • Stefan Falk
    Stefan Falk about 8 years
    @confile I think you're mistaken. This here is supposed to just compare the 24 hours passed from 00:00:00 Coordinated Universal Time (UTC), Thursday, 1 January 1970. If you calculate the module with any long value with % (24*60*60*1000L) you're only left with the number of milliseconds that "fit" into 24 hours.
  • JoachimR
    JoachimR about 8 years
    Calendar.HOUR_OF_DAY is more appropriate (24 hours rather than 12)
  • mabi
    mabi almost 8 years
    Be careful with daylight saving time, when one date is in DST and the other is not, the calculation is off by one hour. If both dates are in the same timezone everything is OK.
  • David R Tribble
    David R Tribble almost 8 years
    @mabi: The internal ticks count returned by getTime() is not aware of, nor affected by DST. If two tick values are equal, they represent the same point in time (the number of msec ticks since the UTC epoch), regardless of the calendar, timezone, or DST setting object they are enclosed within.
  • mabi
    mabi almost 8 years
    @DavidRTribble what is the expected result of comparing 2 February 17:00 and 2 August 17:00? I think it should be zero. This is not the result I get.
  • Rehan Haider
    Rehan Haider almost 6 years
    getTime() GMT based time stamp which may not be suitable for some cases, as if you are living in -1 time zone and you have to compare 22 hours with 23 hours, apparently 22 hours are less than 23 hours but due to time zone difference hetTime() will conert 22 hours to 23 hours and 23 hours to 0 hours and than 23 hours becomes greater than 0 hours.
  • Dibzmania
    Dibzmania almost 6 years
    @RehanHaider I had this issue. But with a little tweak in the code, I think the case can be handled.
  • Basil Bourque
    Basil Bourque over 4 years
    I don't believe this Answer addresses the Question, the rather unclear Question. But, besides that, no need to roll-your-own date-time math in modern Java to calculate elapsed milliseconds between two moments: Duration.between( d1.toInstant() , d2.toInstant() ).toMillis()