17

One thing I want to know is how to calculate what date will it be 10 days from today.

Second thing is to check if one Date is between two other Dates. For example, let's say I have an app that shows what events I need to do in the next 10 days (planner). Now how can I see if the date I assigned to an event is between today and the date that is 10 days from today?

John Topley
  • 113,588
  • 46
  • 195
  • 237
dimitar
  • 375
  • 2
  • 3
  • 6

7 Answers7

20

Manipulating and comparing dates using java.util.Date and java.util.Calendar is pretty a pain, that's why JodaTime exist. None of the answers as far have covered the time in question. The comparisons may fail when the dates have a non-zero time. It's also unclear whether you want an inclusive or exclusive comparison. Most of the answers posted so far suggest exclusive comparision (i.e. May 24 is not between May 20 and May 24) while in real it would make more sense to make it inclusive (i.e. May 24 is between May 20 and May 24).


One thing I want to know is how to calculate what date will it be 10 days from today.

With the standard Java SE 6 API, you need java.util.Calendar for this.

Calendar plus10days = Calendar.getInstance();
plus10days.add(Calendar.DAY_OF_YEAR, 10);

With JodaTime you would do like this:

DateTime plus10days = new DateTime().plusDays(10);

Second thing is to check if one Date is between two other Dates. For example, let's say I have an app that shows what events I need to do in the next 10 days (planner). Now how can I see if the date I assigned to an event is between today and the date that is 10 days from today?

Now comes the terrible part with Calendar. Let's prepare first:

Calendar now = Calendar.getInstance();
Calendar plus10days = Calendar.getInstance();
plus10days.add(Calendar.DAY_OF_YEAR, 10);
Calendar event = Calendar.getInstance();
event.set(year, month - 1, day); // Or setTime(date);

To compare reliably using Calendar#before() and Calendar#after(), we need to get rid of the time first. Imagine it's currently 24 May 2010 at 9.00 AM and that the event's date is set to 24 May 2010 without time. When you want inclusive comparison, you would like to make it return true at the same day. I.e. both the (event.equals(now) || event.after(now)) or -shorter but equally- (!event.before(now)) should return true. But actually none does that due to the presence of the time in now. You need to clear the time in all calendar instances first like follows:

calendar.clear(Calendar.HOUR);
calendar.clear(Calendar.HOUR_OF_DAY);
calendar.clear(Calendar.MINUTE);
calendar.clear(Calendar.SECOND);
calendar.clear(Calendar.MILLISECOND);

Alternatively you can also compare on day/month/year only.

if (event.get(Calendar.YEAR) >= now.get(Calendar.YEAR)
    && event.get(Calendar.MONTH) >= now.get(Calendar.MONTH)
    && event.get(Calendar.DAY_OF_MONTH) >= now.get(Calendar.DAY_OF_MONTH)
{
    // event is equal or after today.
}

Very verbose all.

With JodaTime you can just use DateTime#toLocalDate() to get the date part only:

LocalDate now = new DateTime().toLocalDate();
LocalDate plus10days = now.plusDays(10);
LocalDate event = new DateTime(year, month, day, 0, 0, 0, 0).toLocalDate();
if (!event.isBefore(now) && !event.isAfter(plus10days)) {
    // Event is between now and 10 days (inclusive).
}

Yes, the above is really all you need to do.

BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
16
public static boolean between(Date date, Date dateStart, Date dateEnd) {
    if (date != null && dateStart != null && dateEnd != null) {
        if (date.after(dateStart) && date.before(dateEnd)) {
            return true;
        }
        else {
            return false;
        }
    }
    return false;
}

EDIT: Another suggested variant:

public Boolean checkDate(Date startDate, Date endDate, Date checkDate) { 
    Interval interval = new Interval(new DateTime(startDate), 
                                     new DateTime(endDate));   
    return interval.contains(new DateTime(checkDate)); 
}
9000
  • 39,899
  • 9
  • 66
  • 104
Krish Lakshmanan
  • 760
  • 7
  • 13
5

Use JodaTime calendar replacement classes: http://joda-time.sourceforge.net/

Rune Molin
  • 66
  • 4
  • +1 Specially if you are doing plain date (not datetime) calculation, JodaTime's LocalDate class gives you all you need. – leonbloy May 24 '10 at 13:24
3

You can use before, after and compareTo methods of Date class.

Here're some examples

http://www.roseindia.net/java/example/java/util/CompareDate.shtml

http://www.javafaq.nu/java-example-code-287.html

http://www.esus.com/javaindex/j2se/jdk1.2/javautil/dates/comparingdates.html

And here's API on Date class

http://java.sun.com/j2se/1.4.2/docs/api/java/util/Date.html

Good Luck!

hgulyan
  • 8,099
  • 8
  • 50
  • 75
2

To add ten days:

Date today = new Date();
Calendar cal = new GregorianCalendar();
cal.setTime(today);
cal.add(Calendar.DAY_OF_YEAR, 10);

To check if between two dates:

myDate.after(firstDate) && myDate.before(lastDate);
Andrei Fierbinteanu
  • 7,656
  • 3
  • 31
  • 45
0

I took the initial answer and modified it a bit. I consider if the dates are equal to be "inside"..

private static boolean between(Date date, Date dateStart, Date dateEnd) {
    if (date != null && dateStart != null && dateEnd != null) {
        return (dateEqualOrAfter(date, dateStart) && dateEqualOrBefore(date, dateEnd));

    }
    return false;
}

private static boolean dateEqualOrAfter(Date dateInQuestion, Date date2)
{
    if (dateInQuestion.equals(date2))
        return true;

    return (dateInQuestion.after(date2));

}
private static boolean dateEqualOrBefore(Date dateInQuestion, Date date2)
{
    if (dateInQuestion.equals(date2))
        return true;

    return (dateInQuestion.before(date2));

}
Simon Rolin
  • 940
  • 13
  • 34
technocrat
  • 3,513
  • 5
  • 25
  • 39
0

To check if date is between two dates, here is simple program:

public static void main(String[] args) throws ParseException {

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

    String oeStartDateStr = "04/01/";
    String oeEndDateStr = "11/14/";

    Calendar cal = Calendar.getInstance();
    Integer year = cal.get(Calendar.YEAR);

    oeStartDateStr = oeStartDateStr.concat(year.toString());
    oeEndDateStr = oeEndDateStr.concat(year.toString());

    Date startDate = sdf.parse(oeStartDateStr);
    Date endDate = sdf.parse(oeEndDateStr);
    Date d = new Date();
    String currDt = sdf.format(d);


    if((d.after(startDate) && (d.before(endDate))) || (currDt.equals(sdf.format(startDate)) ||currDt.equals(sdf.format(endDate)))){
        System.out.println("Date is between 1st april to 14th nov...");
    }
    else{
        System.out.println("Date is not between 1st april to 14th nov...");
    }
}
Akshay Lokur
  • 6,680
  • 13
  • 43
  • 62