How to Compare Two Dates Without the Time Portion

How to compare two Dates without the time portion?

Update: while Joda Time was a fine recommendation at the time, use the java.time library from Java 8+ instead where possible.


My preference is to use Joda Time which makes this incredibly easy:

DateTime first = ...;
DateTime second = ...;

LocalDate firstDate = first.toLocalDate();
LocalDate secondDate = second.toLocalDate();

return firstDate.compareTo(secondDate);

EDIT: As noted in comments, if you use DateTimeComparator.getDateOnlyInstance() it's even simpler :)

// TODO: consider extracting the comparator to a field.
return DateTimeComparator.getDateOnlyInstance().compare(first, second);

("Use Joda Time" is the basis of almost all SO questions which ask about java.util.Date or java.util.Calendar. It's a thoroughly superior API. If you're doing anything significant with dates/times, you should really use it if you possibly can.)

If you're absolutely forced to use the built in API, you should create an instance of Calendar with the appropriate date and using the appropriate time zone. You could then set each field in each calendar out of hour, minute, second and millisecond to 0, and compare the resulting times. Definitely icky compared with the Joda solution though :)

The time zone part is important: java.util.Date is always based on UTC. In most cases where I've been interested in a date, that's been a date in a specific time zone. That on its own will force you to use Calendar or Joda Time (unless you want to account for the time zone yourself, which I don't recommend.)

Quick reference for android developers

//Add joda library dependency to your build.gradle file
dependencies {
...
implementation 'joda-time:joda-time:2.9.9'
}

Sample code (example)

DateTimeComparator dateTimeComparator = DateTimeComparator.getDateOnlyInstance();

Date myDateOne = ...;
Date myDateTwo = ...;

int retVal = dateTimeComparator.compare(myDateOne, myDateTwo);

if(retVal == 0)
//both dates are equal
else if(retVal < 0)
//myDateOne is before myDateTwo
else if(retVal > 0)
//myDateOne is after myDateTwo

Comparing date part only without comparing time in JavaScript

I'm still learning JavaScript, and the only way that I've found which works for me to compare two dates without the time is to use the setHours method of the Date object and set the hours, minutes, seconds and milliseconds to zero. Then compare the two dates.

For example,

date1 = new Date()
date2 = new Date(2011,8,20)

date2 will be set with hours, minutes, seconds and milliseconds to zero, but date1 will have them set to the time that date1 was created. To get rid of the hours, minutes, seconds and milliseconds on date1 do the following:

date1.setHours(0,0,0,0)

Now you can compare the two dates as DATES only without worrying about time elements.

Compare date without time

Try compare dates changing to 00:00:00 its time (as this function do):

public static Date getZeroTimeDate(Date fecha) {
Date res = fecha;
Calendar calendar = Calendar.getInstance();

calendar.setTime( fecha );
calendar.set(Calendar.HOUR_OF_DAY, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MILLISECOND, 0);

res = calendar.getTime();

return res;
}

Date currentDate = new Date();// get current date
Date eventDate = tempAppointments.get(i).mStartDate;
int dateMargin = getZeroTimeDate(currentDate).compareTo(getZeroTimeDate(eventDate));

How to compare date time without time portion in C#

You just need to compare DateTime.Today and DateTime.Date:

if(_dateJoin.Date > DateTime.Today)
{
// ...
}
else
{
// ...
}

Update:

object value has date like Date = {03-16-2016 12:00:00 AM} when
execute this line

DateTime _dateJoin =   DateTime.ParseExact(value.ToString(), "MM/dd/yyyy", null);

then i'm getting error like String was not recognized as a valid DateTime. –

That's a different issue, you have to use the correct format provider:

DateTime _dateJoin = DateTime.Parse(value.ToString(), CultureInfo.InvariantCulture);

with ParseExact(not necessary in this case):

DateTime _dateJoin = DateTime.ParseExact(value.ToString(), "MM-dd-yyyy hh:mm:ss tt", CultureInfo.InvariantCulture);

Javascript - Comparing dates without time

The simplest way to get the number of whole days between two dates is to create two date objects for the subject dates that are set to the same time. Noon is convenient as it means the date part is unaffected by daylight saving (some places introduce it at midnight) if you happen to print out just the date part.

The following does all calculations in the time zone of the host system. UTC could be used (and the hours set to 0 as daylight saving isn't an issue at all), but it's more to type.

E.g.:

function differenceInDays(d0, d1) {

// Copy dates so don't affect originals

d0 = new Date(+d0);

d1 = new Date(+d1);

// Set to noon

d0.setHours(12,0,0,0);

d1.setHours(12,0,0,0);

// Get difference in whole days, divide by milliseconds in one day

// and round to remove any daylight saving boundary effects

return Math.round((d1-d0) / 8.64e7)

}

// Difference between 2015-11-12T17:35:32.124 and 2015-12-01T07:15:54.999

document.write(differenceInDays(new Date(2015,10,12,17,35,32,124),

new Date(2015,11,01,07,15,54,999)));

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

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?

  • Java SE 8, Java SE 9, Java SE 10, Java SE 11, and later - Part of the standard Java API with a bundled implementation.

    • Java 9 adds some minor features and fixes.
  • Java SE 6 and Java SE 7
    • Most of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
  • Android
    • Later versions of Android bundle implementations of the java.time classes.
    • For earlier Android (<26), the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….

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.

How to compare dates only (and not the time) in python

d1.date() == d2.date()

From the Python doc:

datetime.date() Return date object with same year, month and day.

Comparing NSDates without time component

Use this Calendar function to compare dates in iOS 8.0+

func compare(_ date1: Date, to date2: Date, toGranularity component: Calendar.Component) -> ComparisonResult


passing .day as the unit

Use this function as follows:

let now = Date()
// "Sep 23, 2015, 10:26 AM"
let olderDate = Date(timeIntervalSinceNow: -10000)
// "Sep 23, 2015, 7:40 AM"

var order = Calendar.current.compare(now, to: olderDate, toGranularity: .hour)

switch order {
case .orderedDescending:
print("DESCENDING")
case .orderedAscending:
print("ASCENDING")
case .orderedSame:
print("SAME")
}

// Compare to hour: DESCENDING

var order = Calendar.current.compare(now, to: olderDate, toGranularity: .day)

switch order {
case .orderedDescending:
print("DESCENDING")
case .orderedAscending:
print("ASCENDING")
case .orderedSame:
print("SAME")
}

// Compare to day: SAME

Compare DATETIME and DATE ignoring time portion

Use the CAST to the new DATE data type in SQL Server 2008 to compare just the date portion:

IF CAST(DateField1 AS DATE) = CAST(DateField2 AS DATE)

Most efficient way to compare two dates; one with time, one without

Yes, use the Date property of the DateTime structure, or just use DateTime.Today.

e.g.

DateTime compareDate = DateTime.Now.Date

or

DateTime compareDate = DateTime.Today 


Related Topics



Leave a reply



Submit