Java check if date is within 7 days

Table of Contents

  • Introduction
  • Date & Local Date Class in Java
  • Check if The Date Is Between Two Dates in Java
    • Using the isAfter() and isBefore() Methods of the Local Date Class in Java
    • Using the compareTo() Method of the Local Date Class in Java
    • Using the after() and before() Methods of the Date Class in Java
    • Using the compare To() Method of the Date Class in Java
    • Using the getTime() Method of The Date Class in Java
    • Using the Joda-Time Library
    • Using the Apache Commons Net Library – Time Stamp Class

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.

Input:

Date_1:21/10/18

Date_2:22/11/18

Date toValidate:13/11/18

Output:

The date13/11/18lies between the dates21/10/18and22/11/18

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.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

importjava.text.ParseException;

importjava.text.SimpleDateFormat;

importjava.time.LocalDate;

import java.util.Date;

publicclassDateExamples{

    publicstaticvoidmain(String[]args) throwsParseException{

        // Date class example

        // Create a SimpleDateFormat reference with different formats

        SimpleDateFormat sdf1= newSimpleDateFormat("dd/MM/yyyy");

        SimpleDateFormat sdf2=newSimpleDateFormat("yyyy/MM/dd");

        //Create date with format dd/mm/yyyy

        Date t1=sdf1.parse("21/12/2018");

        //Create date with format yyyy/mm/dd

        Date t2= sdf2.parse("2019/11/11");

        //Print the dates using the format() method    

        System.out.println("-----------Date Class Example -------------");

        System.out.println(t1);

        System.out.println(sdf1.format(t1));

        System.out.println();

        System.out.println(t2);

        System.out.println(sdf2.format(t2));

        // LocalDate class example

        // Create using of() method.

        LocalDate ld1=LocalDate.of(2021,10, 30);

        // Create using  parse() method

        LocalDate ld2=LocalDate.parse("2010-12-20");

        System.out.println("-----------LocalDate Class Example -----------");

        System.out.println(ld1);

        System.out.println(ld2);

    }

}

-----------Date ClassExample-------------

Fri Dec2100:00:00IST2018

21/12/2018

Mon Nov11 00:00:00IST2019

2019/11/11

-----------LocalDate ClassExample-----------

2021-10-30

2010-12-20

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.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

importjava.time.LocalDate;

publicclassCheckDateBetweenLocalDateMain{

    publicstaticvoid main(String[]args)throwsParseException{

        //Create the Lower and Upper Bound Local Date

                //Format: YYYY-MM-DD

        LocalDate startDate=LocalDate.of(2018,9,21);

        LocalDate endDate= LocalDate.of(2018,10,22);

        //Create the date object to check

        LocalDate dateToValidate= LocalDate.of(2018,10,13);

        //Use the isAfter() and isBefore() method to check date

        if(dateToValidate.isAfter(startDate) && dateToValidate.isBefore(endDate))

        {

System.out.println("The date "+dateToValidate+" lies between the two dates");

        }

        else

        {

System.out.println(dateToValidate+" does not lie between the two dates");

        }

    }

}

The date2018-10-13lies between the two dates

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:

if(!(dateToValidate.isAfter(endDate)||dateToValidate.isBefore(startDate)))

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:

publicintcompareTo(Date anotherDate)

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.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

importjava.time.LocalDate;

publicclassCheckDateBetweenLocalDateMain{

publicstaticvoidmain(String[] args){

      //Create the Lower and Upper Bound Date object

      LocalDate startDate=LocalDate.of(2019,7,18);

      LocalDate endDate=LocalDate.of(2019,12,28);

      //Create the date object to check

      LocalDate dateToValidate= LocalDate.of(2019,8,25);

      //Compare each date and multiply the returned values

      if(startDate.compareTo(dateToValidate) *dateToValidate.compareTo(endDate)>0)

      {

        System.out.println("The date "+dateToValidate+" lies between the two dates");

      }

      else

      {

        System.out.println(dateToValidate+" does not lie between the two dates");

      }

}

}

Output:

The date2019-8-25lies between the two dates

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.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

importjava.text.ParseException;

importjava.text.SimpleDateFormat;

importjava.util.Date;

publicclass CheckDateBetweenTwoDatesMain{

    publicstaticvoidmain(String[]args)throwsParseException{

        // Create a SimpleDateFormat reference with different formats

        SimpleDateFormat sdf=newSimpleDateFormat("dd/MM/yyyy");

        //Create the Lower and Upper Bound Date object

        Date startDate=sdf.parse("21/10/2018");

        Date endDate=sdf.parse("22/11/2018");

        //Create the date object to check

        Date dateToValidate=sdf.parse("13/11/2018");

        //Use the after() and before() method to check date

        if(dateToValidate.after(startDate) && dateToValidate.before(endDate))

        {

            System.out.println("The date "+sdf.format(dateToValidate)+" lies between the two dates");

        }

        else

        {

System.out.println(sdf.format(dateToValidate)+" does not lie between the two dates");

        }

    }

}

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:

if(!(dateToValidate.after(endDate)||dateToValidate.before(startDate)))

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:

publicintcompareTo(Date anotherDate)

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.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

import java.text.ParseException;

import java.text.SimpleDateFormat;

import java.util.Date;

publicclass CheckDateBetweenTwoDatesMain{

publicstaticvoidmain(String[]args)throwsParseException{

      // Create a SimpleDateFormat reference with different formats

      SimpleDateFormat sdf=newSimpleDateFormat("dd/MM/yyyy");

      //Create the Lower and Upper Bound Date object

      Date startDate =sdf.parse("11/07/2019");

      Date endDate=sdf.parse("30/12/2019");

      //Create the date object to check

      Date dateToValidate=sdf.parse("22/08/2019");

      //Compare each date and multiply the returned values

      if(startDate.compareTo(dateToValidate) *dateToValidate.compareTo(endDate)>0)

      {

        System.out.println("The date "+sdf.format(dateToValidate)+" lies between the two dates");

      }

      else

      {

        System.out.println(sdf.format(dateToValidate)+" does not lie between the two dates");

      }

}

}

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.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

importjava.text.ParseException;

importjava.text.SimpleDateFormat;

importjava.util.Date;

publicclass CheckDateUsingGetTimeMain{

    publicstaticvoidmain(String[]args)throwsParseException{

        // Create a SimpleDateFormat reference with different formats

        SimpleDateFormat sdf=newSimpleDateFormat("dd/MM/yyyy");

        //Create the Lower and Upper Bound Date object

        Date startDate=sdf.parse("11/07/2019");

        Date endDate=sdf.parse("30/12/2019");

        //Create the date object to check

        Date dateToValidate=sdf.parse("22/08/2019");

        // Using getTime() method to get each date in milliseconds

        long startDateInMillis=startDate.getTime();

        longendDateInMillis=endDate.getTime();

        long dateInMillis=dateToValidate.getTime();

        // Approach 1: Comparing the millisecond value of each date.

        if(startDateInMillis<= dateInMillis&& dateInMillis <= endDateInMillis )

        {

System.out.println("The date "+sdf.format(dateToValidate)+" lies between the two dates\n");

        }

        else

        {

System.out.println(sdf.format(dateToValidate)+" does not lie between the two dates\n");

        }

        // Approach 2: Subtracting the millisecond values of each date  

        // Create new date to check

        dateToValidate=sdf.parse("21/08/2017");

        dateInMillis= dateToValidate.getTime();

        if(dateInMillis-startDateInMillis>=0&& endDateInMillis - dateInMillis >= 0 )

        {

System.out.println("The date "+sdf.format(dateToValidate)+" lies between the two dates");  

        }

        else

        {

System.out.println(sdf.format(dateToValidate)+" does not lie between the two dates");  

        }

    }

}

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 DateTimeclass and its utility methods of the JodaTime Library by importing with the following maven dependency.

<dependency>

    <groupId>joda-time</groupId>

    <artifactId>joda-time</artifactId>

    <version>2.1</version>

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

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

importjava.text.ParseException;

importjava.text.SimpleDateFormat;

importjava.util.Date;

import org.joda.time.DateTime;

publicclassCheckDateJodaTime{

    publicstaticvoidmain(String[] args)throwsParseException{

        // Create a SimpleDateFormat reference with different formats

        SimpleDateFormat sdf=new SimpleDateFormat("dd/MM/yyyy");

        //Create the Lower and Upper Bound Date object

        Date startDate=sdf.parse("11/07/2019");

        Date endDate=sdf.parse("30/12/2019");

        //Create the date object to check

        Date dateToValidate= sdf.parse("22/08/2019");

        // Create Joda Datetime instance using Date objects

        DateTime dateTime1=newDateTime(startDate);

        DateTime dateTime2=newDateTime(endDate);

        DateTime dateTime3=new DateTime(dateToValidate);

        // compare datetime3 with datetime1 and datetime2 using the methods

        if((dateTime3.isAfter(dateTime1 ))&& ( dateTime3.isBefore( dateTime2 ) ))

        {

System.out.println("The date "+sdf.format(dateToValidate)+" lies between the two dates\n");

        }

        else

        {

System.out.println(sdf.format(dateToValidate)+" does not lie between the two dates\n");

        }

    }

}

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.

<dependency>

  <groupId>commons-net</groupId>

  <artifactId>commons-net</artifactId>

  <version>3.8.0</version>

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

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

importjava.text.ParseException;

importjava.text.SimpleDateFormat;

importjava.util.Date;

import org.apache.commons.net.ntp.TimeStamp;

publicclassCheckDateApacheCommon{

    publicstaticvoid main(String[]args)throwsParseException{

        // Create a SimpleDateFormat reference with different formats

        SimpleDateFormat sdf =newSimpleDateFormat("dd/MM/yyyy");

        //Create the Lower and Upper Bound Date object

        Date startDate= sdf.parse("11/07/2019");

        Date endDate=sdf.parse("30/12/2019");

        //Create the date object to check

        Date dateToValidate=sdf.parse("22/08/2019");

        // Create TimeStamp instance using Date objects

        TimeStamp ts1=new TimeStamp(startDate);

        TimeStamp ts2=newTimeStamp(endDate);

        TimeStamp ts3=new TimeStamp(dateToValidate);

        // Get the total seconds value for each date

        longtime1=ts1.getSeconds();

        long time2=ts2.getSeconds();

        longtime3=ts3.getSeconds();

        // compare time3 with time1 and time2

        if(time1<time3&& time3 < time2 )

        {

System.out.println("The date "+sdf.format(dateToValidate)+" lies between the two dates\n");

        }

        else

        {

System.out.println(sdf.format(dateToValidate)+" does not lie between the two dates\n");

        }

    }

}

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.

How to get 7 days back date in Java?

Use the Calendar-API: // get Calendar instance Calendar cal = Calendar. getInstance(); cal. setTime(new Date()); // substract 7 days // If we give 7 there it will give 8 days back cal.

How to check if time is within a certain range in Java?

Either if you are calling this method using: checkTime("20:11:13", "14:49:00", "01:00:00"); Or using: checkTime("20:11:13", "14:49:00", "05:00:00");.
Simple and elegant! ... .
I tried using this for My Android app, its saying its for only Api26+ , can anyone help? ... .
@AlexMamo which change?.

How to check expiry date in Java?

Check If a String Is a Valid Date in Java.
Overview. In this tutorial, we'll discuss the various ways to check if a String contains a valid date in Java. ... .
Date Validation Overview. ... .
Validate Using DateFormat. ... .
Validate Using LocalDate. ... .
Validate Using DateTimeFormatter. ... .
Validate Using Apache Commons Validator. ... .
Conclusion..

How to calculate 30 days from a date in Java?

LocalDate now = LocalDate. now(); LocalDate thirty = now. minusDays( 30 ); LocalDate sixty = now. minusDays( 60 ); LocalDate ninety = now.

Chủ đề