0

How can I check if a given startdate & enddate cuts a specific time period (train time).

I did following:

if ((startdate >= train.getStartDate()) &&
 (enddate <= train.getEndDate())) {
   // doSomething();
}

doSomething() get only executed, when the time is exact between the given time period. But I want also that doSomething() get executed, when the times are overlapped.

For example:

  • Startdate: 14.10.2015 15.00
  • Enddate: 16.10.2015 17.00
  • Timeperiod: 15.10.2015 10.00 - 19.10.2015 10.00

In this case its overlapping and I want that doSomething() get executed. Any solutions?

Matej
  • 147
  • 2
  • 12

3 Answers3

0

If you want to stick with long-values, I would do the following

if (!((train.getEndDate() < startdate) || (train.getStartDate() > enddate))) {...}

Alternatively, you might want to convert your long-vales to java.util.Date (new Date(long value)) so that you can use the Date-class.

There is also the very nice Joda time 2.2 API which has an Interval-class that provides the following function

overlap(ReadableInterval interval)
      Gets the overlap between this interval and another interval.
F. Knorr
  • 3,045
  • 15
  • 22
0

Date has after and before methods

    if (yourDate.after(startDate) && yourDate.before(endDate)) {
        //doSomething
    }
Saravana
  • 12,647
  • 2
  • 39
  • 57
0

You could try with Guava Ranges too. Here is an example:

public class RangesTest {

SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyyy HH.mm");

@Test
public void testDateRange() throws ParseException {
    Range<Date> timePeriod = createClosedDateRange("15.10.2015 10.00","19.10.2015 10.00");

    assertTrue(timePeriod.isConnected(createClosedDateRange("14.10.2015 15.00", "16.10.2015 17.00")));
    assertTrue(timePeriod.isConnected(createClosedDateRange("14.10.2015 15.00", "20.10.2015 17.00")));
    assertFalse(timePeriod.isConnected(createClosedDateRange("14.10.2015 15.00", "15.10.2015 09.59")));
    assertFalse(timePeriod.isConnected(createClosedDateRange("20.10.2015 17.01", "21.10.2015 17.00")));
}

private Range<Date> createClosedDateRange(String startDate, String endDate) throws ParseException {
    Date startdate= sdf.parse(startDate);
    Date enddate = sdf.parse(endDate);
    return Range.closed(startdate, enddate);
}

}