Check if Date Is Between Two Dates in Java

Introduction

In this article, we will discuss and dwell on how to compare dates in Java. The problem statement is : Check if a Date is between two dates in Java. This roughly translates to Given a date, we need to check if it lies between the range of two dates. Let us understand this with a sample input example.

We will discuss different solutions to this problem in great depth and detail to make it captivating. Let us first have a quick look at how Dates are represented in Java.

Date & Local Date Class in Java

In Java, we can represent Dates as text in a Stringtype variable. But using a String would make formatting the date for different operations very resilient. So, to avoid this Java provides the Date and LocalDate class to perform operations on a Date meta type easily.

Date Class in Java

It is present in java.util package. We can create a date of any format (DD/MM/YYYYY, MM/DD/YYYY, YYYY/MM/DD, etc.) using the SimpleDateFormat class and instantiate it to a Date class object using the parse() method of the SimpleDateFormat class.

LocalDate class in Java

It is present in java.time package. We can create a date of only a specific format i.e. YYYY-MM-DD. We instantiate the LocalDate object using the of() method and pass the relevant parameters to it.

We can also create a LocalDate object using the parse() method where we need to pass the required Date as a String in the format YYYY-MM-DD.

Let us see the sample code to create custom dates using the classes above. It is important to get an idea as we will look at more examples related to this.

Check if The Date Is Between Two Dates in Java

Now, we outline different approaches for the solution to this problem. For some of the approaches, we will undertake the Date values only in the format: DD/MM/YYYY. However, it will support other date formats.

Using the isAfter() and isBefore() Methods of the Local Date Class in Java

The LocalDate class in Java provides the isAfter() method to check if a date lies after the given date and the isBefore() method to check if the date lies before. We call these methods with the date to check and pass the argument date.

We can combine these two methods to Check if a date is between two given dates.

Important points to note:

  • We will take three variables startDate, endDate, and dateToValidate as LocalDate instances and create them using the of() method.
  • We check if the dateToValidate lies after the startDate and if dateToValidate lies before the endDate. If the condition satisfies we print the date is validated.
  • We call the isAfter() and isBefore() methods with the dateToValidate object providing the start and end dates respectively to ensure the check.

Let us look at the code for this approach.

If we need to include the endpoints of the start dates and end dates respectively, we can replace the if condition with this line of code:

Using the compareTo() Method of the Local Date Class in Java

The LocalDate class in Java provides the compareTo() method with which we can compare dates easily based on the return value. Here, we can use this method to Check if the date lies between two dates.

The syntax of the method:

The compareTo() method has the following restrictions:

  • It returns the value 0 if the argument anotherDate is equal to this Date.
  • It returns value < 0 (i.e. -1) if this Date is before the anotherDate argument.
  • It returns a value > 0 (i.e. +1) if this Date is after the anotherDate argument.

Important points to note:

  • We compare the startDate with the dateToValidate and the dateToValidate with the endDate.
  • It returns values +1(if greater) or -1(if smaller) based on the comparison. We then multiply the returned values from both expressions.
  • If the resultant value is greater than 0 it means the date lies within the range otherwise it is not valid.

Let us look at the code.

Output:

Using the after() and before() Methods of the Date Class in Java

The Date class in Java provides the after() method to check if a date lies after the given date and the before() method to check if the date lies before. We can combine these two methods to Check if a date is between two dates.

Important points to note:

  • We will take three variables startDate, endDate, and dateToValidate as Date objects using the parse() method of SimpleDateFormat class.
  • We check if the dateToValidate lies after the startDate and if dateToValidate lies before the endDate. If the condition satisfies we print the date is validated.
  • We call the after() and before() methods with the dateToValidate object providing the start and end dates respectively to ensure the check.

Note: The parse() method of SimpleDateFormat throws ParseException so ensure that the throws declaration is given in the calling method or implemented.

Let us look at the code snippet for this approach.

Output:

While validating, If we need to include the endpoints of the start dates and end dates respectively, we can replace the if condition with this line of code:

Using the compare To() Method of the Date Class in Java

Similar to the LocalDate class, the Date class in Java also provides the compareTo() method which we can use to compare dates easily and Check if the date lies between two dates.

The syntax of the method:

The compareTo() method has the same restrictions as discussed above for the LocalDate class.

Important points to note:

  • We compare the startDate with the dateToValidate and the dateToValidate with the endDate.
  • It returns values +1(if greater) or -1(is smaller) based on the comparison. We then multiply the returned values from both expressions.
  • If the value is greater than 0 it means the date lies within the range otherwise it is not valid.

Let us look at the code snippet for this approach as well.

Output:

Using the getTime() Method of The Date Class in Java

We can also use the getTime() method of the Date class to check if the date is between two dates. The getTime() method converts a Date into its equivalent milliseconds since January 1, 1970. The return value is of type Long.

There are two ways we can solve this using the getTime() method:

  1. We can compute the total millisecond value for each of the dates and compare the dateToValidate with the startDate and endDate respectively.
  2. To validate the dates, we can subtract the millisecond value of dateToValidate with and from the start and end dates respectively.

Note: This approach would not work as expected if we compare dates before January 1, 1970. In such case, the getTime() method will give a negative value on crossing the Long limit.

Let us look at the implementation of these approaches in code.

Output:

Using the Joda-Time Library

Before Java 8, The legacy date and time classes in Java were equipped poorly with minimal utilities. The Joda-Time provides a quality replacement for these Java Date and Time classes. Here, to Check if the date lies between two dates we can use the inbuilt functionality of this package.

We can use the DateTime class and its utility methods of the JodaTime Library by importing with the following maven dependency.

For ease, we will use the JAR file component of the Joda-Time package in our code. You can download the Joda-Time Library JAR from the embedded link. Now, let us look into the steps.

  • We will create three instances of the DateTime class initializing it with the Date objects startDate, endDate, and dateToValidate respectively.
  • The DateTime class provides the isAfter() and isBefore() utility methods, we then compare the Datetime instance of dateToValidate Date object and validate the same using these methods.

Let us have a quick look at the implementation of this approach as well.

Output:

Using the Apache Commons Net Library – Time Stamp Class

The Apache Commons API provides powerful and reusable Java components and dependencies that we can embed into our applications and programs. Here, to check if the Date lies between two dates we can use the inbuilt functionality of this package.

We can use the TimeStamp class of the Net package of Apache Commons Library by importing with the following maven dependency.

For ease, we will use the JAR file component of the Apache Commons Net package in our code. We can download the Apache Commons Net JAR to set up the JAR file component for this package.

Now, let us look into the steps:

  • We will create three instances of the TimeStamp class initializing it with the Date objects startDate, endDate, and dateToValidate respectively.
  • For each TimeStamp object that we create, we calculate the total seconds using the getSeconds() method.
  • The getseconds() calculates the total seconds from the given date to the present date and returns the value of type long.
  • Then compare the total second value of the TimeStamp instance of dateToValidate with other dates and validate it.

Let us look at the implementation of the approach in code.

Output:

That’s all for the article, we discussed 7 ways to Check if a Date lies between two dates in java in detail with code and working examples. You can try these examples out in your Local IDE for a clear understanding.

Feel free to reach out to us for any queries/suggestions.

Was this post helpful?

Related Posts

  • 05 October

    Find Difference Between Two Instant in Java

    Table of ContentsWays to find difference between two Instant in JavaUsing Instant’s until() methodUsing ChronoUnit EnumUsing Duration’s between() method In this post, we will see how to find difference between two Instant in Java. Ways to find difference between two Instant in Java There are multiple ways to find difference between two Instant in various […]

  • 05 October

    Find Difference Between Two LocalDate in Java

    Table of ContentsWays to find difference between two LocalDate in JavaUsing LocalDate’s until() methodUsing ChronoUnit EnumUsing Duration’s between() methodUsing Period’s between() methodFrequently asked questionsHow to find difference between two LocalDate in Java in Days?How to find difference between two LocalDate in Java in Years?How to find difference between two LocalDate in Java in Months?How to […]

  • 26 September

    Get List of Weekday Names in Java

    Table of ContentsUsing DateFormatSymbols’s getWeekdays() methodUsing DateFormatSymbols’s getShortWeekdays() method [For short names]Using DateFormatSymbols’s getWeekdays() with Locale In this post, we will see how to get list of weekday names in Java. Using DateFormatSymbols’s getWeekdays() method We can use DateFormatSymbols's getWeekdays() to get list of weekday names in Java. It will provide complete weekday names like […]

  • 24 September

    Get List of Month Names in Java

    Table of ContentsUsing DateFormatSymbols’s getMonth() methodUsing DateFormatSymbols’s getShortMonths() method [ For short names]Using DateFormatSymbols’s getMonth() with Locale In this post, we will see how to get list of months name in Java. Using DateFormatSymbols’s getMonth() method We can use DateFormatSymbols's getMonth() to get list of months in Java. It will provide complete month names like […]

  • 20 September

    Get Unix Timestamp in Java

    Table of ContentsWays to get unix timestamp in JavaUsing Instant classUsing System.currentTimeMillis()Using Date’s getTime() methodConvert Date to unix timestamp in JavaUsing Instant classUsing Date’s getTime() method In this post, we will get unix timestamp in Java. As per wikipedia Unix time is a system for describing a point in time. It is the number of […]

  • 17 September

    Check if Date Is Weekend or Weekday in Java

    Table of ContentsUsing LocalDate’s getDayOfWeek() methodUsing LocalDate with DayOfWeekUsing Date and Calendar classes In this post, we will see how to check if Date is weekend or weekday in Java. Please note that we will consider Saturaday/Sunday as weekend and rest five days of week as weekdays. Using LocalDate’s getDayOfWeek() method We can use LocalDate’s […]

Leave a Reply

Your email address will not be published. Required fields are marked *

Subscribe to our newletter

Get quality tutorials to your inbox. Subscribe now.