1

I have a date and a number and want to check if this date and this number occurs in a list of other dates within:

  • +-20 date intervall with the same number

so for example 1, 1.1.2013 and 1,3.1.2013 should reuturn false.

I tried to implement the method something like that:

private List<EventDate> dayIntervall(List<EventDate> eventList) throws Exception {
    List<EventDate> resultList = new ArrayList<EventDate>();

    for (int i = 0; i < eventList.size(); i++) {
        String string = eventList.get(i).getDate();
        Date equalDate = new SimpleDateFormat("dd.MM.yyyy", Locale.GERMAN).parse(string);
        for (int j = 0; j < eventList.size(); j++) {
            String string1 = eventList.get(i).getDate();
            Date otherDate = new SimpleDateFormat("dd.MM.yyyy", Locale.GERMAN).parse(string1);
            if (check number of i with number of j && check Date) {
                //do magic
            }
        }

    }

    return resultList;
}

The construction of the iteration method is not that hard. What is hard for me is the date intervall checking part. I tried it like that:

boolean isWithinRange(Date testDate, Date days) {
           return !(testDate.before(days) || testDate.after(days));
    }

However that does not work because days are not takes as days. Any suggestions on how to fix that?

I really appreciate your answer!

user2051347
  • 1,609
  • 4
  • 23
  • 34
  • If your date format is `dd.MM.yyyy` and you want to check if two dates are within twenty days of each other, shouldn't you return `true` for `1.1.2013` and `3.1.2013`? – gdejohn Feb 11 '14 at 08:59

3 Answers3

1

You should avoid java.util.Date if at all possible. Using the backport of ThreeTen (the long awaited replacement date/time API coming in JDK8), you can get the number of days between two dates like so:

int daysBetween(LocalDate start, LocalDate end) {
    return Math.abs(start.periodUntil(end).getDays());
}

Does that help?

gdejohn
  • 7,451
  • 1
  • 33
  • 49
1

You can get the number of dates in between the 2 dates and compare with your days parameter. Using Joda-Time API it is relatively an easy task: How do I calculate the difference between two dates?.

Code:

SimpleDateFormat format = new SimpleDateFormat("dd.MM.yyyy", Locale.GERMAN);

Date startDate = format.parse("1.1.2013");
Date endDate = format.parse("3.1.2013");

Days d = Days.daysBetween(new DateTime(startDate), new DateTime(endDate));
System.out.println(d.getDays());

Gives,

2

This is possible using Calendar class as well:

Calendar cal = Calendar.getInstance();
cal.setTime(startDate);
System.out.println(cal.fieldDifference(endDate, Calendar.DAY_OF_YEAR));

Gives,

2

This 2 can now be compared to your actual value (20).

Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
StoopidDonut
  • 8,547
  • 2
  • 33
  • 51
  • @gdejohn I don't think having a valid alternative is doing any harm here? – StoopidDonut Feb 11 '14 at 08:58
  • I didn't say it was doing any harm, and I didn't mean for you or anyone to infer that. I was just wondering exactly what I asked. Sorry for the misunderstanding. – gdejohn Feb 11 '14 at 09:01
  • @gdejohn no worries at all, I was in fact unaware of ThreeTen backport for 7. Though I am aware of JSR-310 capabilities and the vast improvements, discussions which I have been part of for various problems not overcome by joda - like [here](http://stackoverflow.com/questions/21023907/cant-get-correct-current-islamic-date). – StoopidDonut Feb 11 '14 at 09:13
  • Beware that the *backport* (to Java 7) of ThreeTen may not be ready for production use – I'm not sure of its status, I'm merely cautioning you to check. The Oracle-backed implementation being bundled with Java 8 is in final testing now. Joda-Time is still alive and worthwhile, useful for projects in Java 7 and earlier. And those projects will continue to run in Java 8. Joda-Time is actively maintained. Eventually Joda-Time will be supplanted by the [java.time.* package](http://download.java.net/jdk8/docs/api/java/time/package-summary.html) but that day is some years away. – Basil Bourque Feb 11 '14 at 11:06
  • @BasilBourque, why would that be years away? JSR-310 is supposed to address design flaws in Joda-Time and should be production-ready in, like, a month when it's made available as part of Java 8. – gdejohn Feb 11 '14 at 21:20
1

You question is difficult to follow. But given its title, perhaps this will help…

Span Of Time In Joda-Time

The Joda-Time library provides a trio of classes to represent a span of time: Interval, Period, and Duration.

Interval

An Interval object has specific endpoints that lie on the timeline of the Universe. A handy contains method tells if a DateTime object occurs within those endpoints. The beginning endpoint in inclusive while the last endpoint is exclusive.

Time Zones

Note that time zones are important, for handling Daylight Saving Time and other anomalies, and for handling start-of-day. Keep in mind that while a java.util.Date seems like it has a time zone but does not, a DateTime truly does know its own time zone.

Sample Code

Some code off the top of my head (untested)…

DateTimeZone timeZone = DateTimeZone.forID( "Europe/Berlin" );
DateTime dateTime = new DateTime( yourDateGoesHere, timeZone );
Interval interval = new Interval( dateTime.minusDays( 20 ), dateTime.plusDays( 20 ) );
boolean didEventOccurDuringInterval = interval.contains( someOtherDateTime );

Whole Days

If you want whole days, call the withTimeAtStartOfDay method to get first moment of the day. In this case, you probably need to add 21 rather than 20 days for the ending point. As I said above, the end point is exclusive. So if you want whole days, you need the first moment after the time period you care about. You need the moment after the stroke of midnight. If this does not make sense, see my answers to other questions here and here.

Note that Joda-Time includes some "midnight"-related methods and classes. Those are no longer recommended by the Joda team. The "withTimeAtStartOfDay" method takes their place.

DateTime start = dateTime.minusDays( 20 ).withTimeAtStartOfDay();
DateTime stop = dateTime.plusDays( 21 ).withTimeAtStartOfDay(); // 21, not 20, for whole days.
Interval interval = new Interval( start, stop );
Community
  • 1
  • 1
Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154