Check whether a given date lies between other two dates in java



Contents of page :
  • Program 1 - Check whether a given date lies between other two dates (where dates are manually created using dd-MM-yyyy format)

Program 1 - Check whether a given date lies between other two dates (where dates are manually created using dd-MM-yyyy format)


import java.util.Date;
import java.text.ParseException;
import java.text.SimpleDateFormat;
/** Copyright (c), AnkitMittal JavaMadeSoEasy.com */
public class DateTest {
   public static void main(String... args) {
          try {
                 SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");
                 sdf.setLenient(false);
                 Date d1 = sdf.parse("11-12-2015");
                 Date d2 = sdf.parse("15-12-2015");
                 Date d3 = sdf.parse("18-12-2015");
                 if (d2.compareTo(d1) >= 0) {
                       if (d2.compareTo(d3) <= 0) {
                              System.out.println("d2 is in between d1 and d2");
                       } else {
                              System.out.println("d2 is NOT in between d1 and d2");
                       }
                 } else {
                       System.out.println("d2 is NOT in between d1 and d2");
                 }
          } catch (ParseException pe) {
                 pe.printStackTrace();
          }
   }
}
/*OUTPUT
d2 is in between d1 and d2
*/


Now let’s test the above program with below dates >

                   Date d1 = sdf.parse("11-12-2015");
                 Date d2 = sdf.parse("19-12-2015");
                 Date d3 = sdf.parse("18-12-2015");

Output of above program will be >
d2 is NOT in between d1 and d2



RELATED LINKS>

Creating Date manually - by passing users parameter>

Forming date MANUALLY using java.util.Date’s constructor, GregorianCalendar’s constructor and set method in java



Convert String to Date>

Using SimpleDateFormat to convert String to Date - pass date, month, year, hour, minute, second, day, Am/Pm(E), time zone(z) || Enabling strict parsing of String by setting SimpleDateFormat’s setLenient(false)



Difference between two Dates>

2 approaches to check whether difference between given two dates is greater than specified number of days or not


No comments:

Post a Comment