How to compare dates in Java?
Date has before and after methods and can be compared to each other as follows:
if(todayDate.after(historyDate) && todayDate.before(futureDate)) {
// In between
}
For an inclusive comparison:
if(!historyDate.after(todayDate) && !futureDate.before(todayDate)) {
/* historyDate <= todayDate <= futureDate */
}
You could also give Joda-Time a go, but note that:
Joda-Time is the de facto standard date and time library for Java prior to Java SE 8. Users are now asked to migrate to java.time (JSR-310).
Back-ports are available for Java 6 and 7 as well as Android.
How to compare two string dates in Java?
Convert them to an actual Date
object, then call before
.
SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd h:m");
System.out.println(sdf.parse(startDate).before(sdf.parse(endDate)));
Recall that parse
will throw a ParseException
, so you should either catch it in this code block, or declare it to be thrown as part of your method signature.
How to compare two dates along with time in java
Since Date
implements Comparable<Date>
, it is as easy as:
date1.compareTo(date2);
As the Comparable
contract stipulates, it will return a negative integer/zero/positive integer if date1
is considered less than/the same as/greater than date2
respectively (ie, before/same/after in this case).
Note that Date
has also .after()
and .before()
methods which will return booleans instead.
How to compare dates in Java using comparison operators?
LocalDate date1 = LocalDate.of(2017, 10, 30); // Year, month, day.
LocalDate date2 = LocalDate.of(2017, 10, 31);
LocalDate date3 = LocalDate.of(2018, 10, 30);
System.out.printf("%s before %s? %s%n", date1, date2, date1.isBefore(date2));
System.out.printf("%s before %s? %s%n", date2, date3, date3.isBefore(date3));
System.out.printf("%s before %s? %s%n", date3, date1, date3.isBefore(date1));
If you want to know how to do a comparison yourself:
- Compare first year, then month, then day: from most significant to least
- For this reason the ISO standard of denoting dates (and times) is
2017-09-30T13:05:01,000
where a text comparison with a representation of the same length suffices.
And the pattern goes:
- if years not equal then result found
- if months not equal then result found
- result is comparison of days
Comparing dates as strings in Java
Since your dates are in the YYYY-MM-DD
format, a lexicographic comparison can be used to determine the ordering between two dates. Thus, you can just use the String.compareTo()
method to compare the strings:
int c1 = objectDate.compareTo(dateOne);
int c2 = objectDate.compareTo(dateTwo);
if ((c1 >= 0 && c2 <= 0) || (c1 <= 0 && c2 >= 0)) {
// objectDate between dateOne and dateTwo (inclusive)
}
If it is guaranteed that dateOne < dateTwo
, then you can just use (c1 >= 0 && c2 <= 0)
. To exclude the date bounds, use strict inequalities (>
and <
).
How to compare two dates in String format?
For a more generic approach, you can convert them both to Date
objects of a defined format, and then use the appropriate methods:
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
Date date1 = format.parse(date1);
Date date2 = format.parse(date2);
if (date1.compareTo(date2) <= 0) {
System.out.println("earlier");
}
Java Date comparison: Dates in different formats
tl;dr
LocalDate
.parse( "2018-08-29" )
.isEqual(
OffsetDateTime
.parse( "2018-08-30T00:00:00+10:00" )
.toLocalDate()
)
false
java.time
Parse each input during its appropriate type in java.time.
LocalDate ld = LocalDate.parse( "2018-08-29" ) ;
OffsetDateTime odt = OffsetDateTime.parse( "2018-08-30T00:00:00+10:00" ) ;
Compare by extracting a LocalDate
from the OffsetDateTime
.
Boolean sameDate = ld.isEqual( odt.toLocalDate() ) ;
false
Or perhaps you want to adjust that OffsetDateTime
from its offset of ten hours ahead of UTC to another offset or time zone. For example, let’s adjust back to UTC before extracting a date to compare.
LocalDate
.parse( "2018-08-29" )
.isEqual(
OffsetDateTime
.parse( "2018-08-30T00:00:00+10:00" )
.withOffsetSameInstant( ZoneOffset.UTC )
.toLocalDate()
)
This changes our results from false
, seen in code above, to true
.
true
Comparing dates in Java
Java has a Date
object. You should be using that instead.
import java.util.Calendar;
import java.util.Date;
public class CompareDates {
public static void main(String[] args) {
// Create a calendar, this will default to today
Calendar cal = Calendar.getInstance();
// Subtract 1 day
cal.add(Calendar.DATE, -1);
// Compare the result (1)
System.out.println(dateCompare(new Date(), cal.getTime()));
// Add 2 days
cal.add(Calendar.DATE, 2);
// Compare the result (-1)
System.out.println(dateCompare(new Date(), cal.getTime()));
}
public static int dateCompare(Date today, Date date2) {
System.out.println("Compare " + today + " with " + date2);
return today.compareTo(date2);
}
}
You could also just make use of the Date
API and use before
and after
...
Date now = new Date();
Calendar cal = Calendar.getInstance();
cal.add(Calendar.DATE, -1);
System.out.println(now + " isBefore " + cal.getTime() + " = " + now.before(cal.getTime()));
System.out.println(now + " isAfter " + cal.getTime() + " = " + now.after(cal.getTime()));
cal.add(Calendar.DATE, 2);
System.out.println(now + " isBefore " + cal.getTime() + " = " + now.before(cal.getTime()));
System.out.println(now + " isAfter " + cal.getTime() + " = " + now.after(cal.getTime()));
Related Topics
Why Do I Need to Override the Equals and Hashcode Methods in Java
How to Append Text to an Existing File in Java
Java Inner Class and Static Nested Class
How Are Anonymous Inner Classes Used in Java
How to Solve "Java.Lang.Noclassdeffounderror"
How to Read a Large Text File Line by Line Using Java
How to Create a File and Write to It
How to Import the Javax.Servlet/Jakarta.Servlet API in My Eclipse Project
How to Read/Convert an Inputstream into a String in Java
How to Avoid Arrayindexoutofboundsexception or Indexoutofboundsexception
Why Is It Frowned Upon to Use a Null Layout in Swing
Trusting All Certificates Using Httpclient Over Https
How to Add Local Jar Files to a Maven Project
How to Properly Stop the Thread in Java
Jtable Duplicate Values in Row
"Non-Static Method Cannot Be Referenced from a Static Context" Error
How to Upload a File Using Java Httpclient Library Working With PHP