-1

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

Date startDate, endDate, dateToCheck;
if (dateToCheck.equals(startDate) || dateToCheck.equals(endDate) || 
    (dateToCheck.after(startDate) && dateToCheck.before(endDate)) 
LuCio
  • 4,285
  • 1
  • 15
  • 29
yasin
  • 47
  • 1
  • 8
  • 3
    Don't use `java.util.Date`. You should use the `java.time` APIs if you're on Java 8 or higher. – marstran Oct 15 '18 at 11:54
  • @marstran can u share code. I can not find. Thanks. – yasin Oct 15 '18 at 11:57
  • @yasin Have you got a search engine? Anyway you may start [here: Oracle tutorial](https://docs.oracle.com/javase/tutorial/datetime/) (includes code). – Ole V.V. Oct 15 '18 at 12:29
  • Also does your code work? It looks reasonable (except for using the outdated and poorly designed `Date` class). If it doesn’t, it’s probably because the `Date` despite its name doesn’t represent a date, so the straightforward solution is to move to `LocalDate` from java.time anyway. – Ole V.V. Oct 15 '18 at 12:32

6 Answers6

3

Just another version of MadProgrammers answer:

    LocalDate startDate = LocalDate.of(2018, Month.OCTOBER, 15);
    LocalDate endDate   = LocalDate.of(2018, Month.OCTOBER, 31); 
    LocalDate dateToCheck = LocalDate.of(2018, Month.OCTOBER, 20);
    if (!dateToCheck.isBefore(startDate) && !dateToCheck.isAfter (endDate))
        System.out.println("In between!");
Eritrean
  • 9,903
  • 1
  • 15
  • 20
  • 1
    Your check is an "exclusive" check, where as I'm doing an "inclusive" check (not a criticism, just a highlight) – MadProgrammer Oct 15 '18 at 19:49
  • 1
    @MadProgrammer Not so. This answer uses the common trick of using “not before” meaning “on or after” and similarly “not after” for “before or on”. So it does check whether the date is in the inclusive range.It does give the same result as your answer. – Ole V.V. Oct 16 '18 at 03:58
  • @OleV.V. I'll stand corrected, but then I would say, the readability suffers :P – MadProgrammer Oct 16 '18 at 05:49
3

tl;dr

LocalDateRange
.of(
    LocalDate.of( 2018 , 1 , 23 ) ,
    LocalDate.parse( "30-03-2018" , DateTimeFormatter.ofPattern( "dd-MM-uuuu" ) 
)
.contains(
    LocalDate.of( 2018 , Month.MARCH , 23 ) 
)

LocalDateRange

The ThreeTen-Extra project adds functionality to the java.time classes built into Java.

Among its classes is two for representing a span-of-time:

  • LocalDateRange
  • Interval

Both have several handy comparison methods such as abuts, overlaps, and contains.


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?

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.

Basil Bourque
  • 218,480
  • 72
  • 657
  • 915
  • Like to see this part of the JDK, because it's not useful or anything – MadProgrammer Oct 15 '18 at 19:53
  • 1
    @MadProgrammer Clarification: This answer does not present a "part of the JDK", but suggests to use an external library which is outside of JDK the same way as any other java library with interval support. And attention: The suggested class `LocalDateRange` supports by standard exclusive end dates (which is strange in the world of calendar dates) and can only accept inclusive dates by a hackish approach (using the factory method `ofClosed(...)`). – Meno Hochschild Oct 16 '18 at 11:10
1

Using java.time (as of Java 8):

LocalDateTime dateToCheck = LocalDateTime.now();
LocalDateTime startDate = dateToCheck.minusHours(1);
LocalDateTime endDate = dateToCheck.plusDays(1);
boolean isOnOrBetween = dateToCheck.compareTo(startDate) >= 0 && dateToCheck.compareTo(endDate) <= 0;

If you need to compare dates from different time zones, use ZonedDateTime instead of LocalDateTime. This solution will take the time into account like the Date in the question does.

LuCio
  • 4,285
  • 1
  • 15
  • 29
  • I personally find `isBefore`and `isAfter` clearer to read than an interpretation of the numeric result from `compareTo`. Then again, MadProgrammer misread Eritrean’s answer using just those, where probably no one will misread `>=` for `>`. So this answer has its advantages too. Also your variable name, `isOnOrBetween`, is very informative. – Ole V.V. Oct 16 '18 at 04:04
  • 1
    @OleV.V. I was thinking about using `isBefore` and `isAfter` too. Since the question is about an including _between_ using `compareTo` results in a shorter expression. Both dates need to be evaluated only once in contrast to using `isBefore` / `isAfter` and additionally `equals`. But you're right, the latter approach reads more naturally. – LuCio Oct 16 '18 at 06:02
1

At a very basic level, something like...

LocalDate monday = LocalDate.now().with(TemporalAdjusters.previousOrSame(DayOfWeek.MONDAY));
LocalDate friday = monday.with(TemporalAdjusters.next(DayOfWeek.FRIDAY));

LocalDate today = LocalDate.now();

if ((friday.isAfter(today) || friday.equals(today)) 
                && (monday.isBefore(today) || monday.equals(today))) {
    System.out.println("between");
} 

I was hoping for something like "interval", but apparently we're not there yet :/

MadProgrammer
  • 323,026
  • 21
  • 204
  • 329
  • @ MadProgrammer To avoid the `equals` checks you can change it to `if (!today.isBefore(monday) && !today.isAfter(friday))` – Eritrean Oct 15 '18 at 12:31
  • Here is an [answer](https://stackoverflow.com/a/21474646/2838289) which is using a type `Interval`. But it's using Joda-Time. – LuCio Oct 15 '18 at 12:31
  • @MadProgrammer this seems to will work, I'll try it thanks – yasin Oct 15 '18 at 12:35
  • There is `java.time.Period`... Did you think about that when you said 'interval'? – zlakad Oct 15 '18 at 13:05
  • @zlakad Yes I looked at `Period`, but it doesn't contain any functionality (that I could see) that would allow me to determine if a date fell within it – MadProgrammer Oct 15 '18 at 19:47
  • @MadProgrammer `Period(someDate, otherDate).isNegative()`? I'd like to see what do you think about this method? – zlakad Oct 15 '18 at 19:50
  • @zlakad Not sure how that ties three dates together? – MadProgrammer Oct 15 '18 at 19:51
  • @MadProgrammer First you check is startDate between checkDate isNegative, then you check if checkDate between endDate isNegative? But, while the second parameter is exclusive we can addDays(1). I,m not sure, just asking is this something like the 'interval'? – zlakad Oct 15 '18 at 19:55
  • [Period.between](https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/time/Period.html#between(java.time.LocalDate,java.time.LocalDate)) – zlakad Oct 15 '18 at 20:03
  • I don't know if it's more efficient or not, but it is it as easily readable? I'd still prefer something like `interval.of(startDate, endDate).contains(date)`, I'm how simple is that?! Basil makes a couple of good suggestions for the 310 backport API - I mean, really, if I was doing something like this on a regular bases, I'd write my own class – MadProgrammer Oct 15 '18 at 21:19
1

Streams – datesUntil & anyMatch

Another solution using java.time and Stream taking only the date into account:

LocalDate dateToCheck = LocalDate.now();
LocalDate startDate = LocalDate.of(2018, 6, 22);
LocalDate endDate = dateToCheck.plusMonths(3);
boolean between = startDate.datesUntil(endDate.plusDays(1)).anyMatch(dateToCheck::equals);
if (between) {
    System.out.println("between");
}
Basil Bourque
  • 218,480
  • 72
  • 657
  • 915
LuCio
  • 4,285
  • 1
  • 15
  • 29
0
## Classic method ##
    import java.util.Date;
    import java.text.ParseException;
    import java.text.SimpleDateFormat;

    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
yasin
  • 47
  • 1
  • 8
  • That’s classic to say the least. No reason to use it in Java 9 or 10 (and I personally would not after Java 1.4). – Ole V.V. Oct 15 '18 at 12:35