0

In a JSP page I have four sample dates like 01- dec , 15- dec, 30- dec and 15- jan. I need to check whether the date above and current date's difference is 15.

Here is my attempt:

    Calendar calendar = Calendar.getInstance();
    Calendar calendar1 = Calendar.getInstance();
    Calendar calendar2 = Calendar.getInstance();
    Calendar calendar3 = Calendar.getInstance();
    Calendar calendar4 = Calendar.getInstance();

    calendar1.set(2011, 11, 02);
    calendar2.set(2011, 06, 02);
    calendar3.set(2011, 09, 07);
    calendar4.set(2011, 06, 05);

    long milliseconds1 = calendar1.getTimeInMillis();
    long milliseconds2 = calendar.getTimeInMillis();

    long diff = milliseconds2 - milliseconds1;
    long diffDays = diff / (24 * 60 * 60 * 1000);

    if (diffDays <= 15) {
        System.out.println("Fifteen");
    } else {
        System.out.println("No Fifteen");
            }

I've to check the condition for all the four scenarios whether the difference is 15 or not. Putting those calendar instances in a map or an list. I don't know how to do it.

BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
Chetan
  • 1,590
  • 3
  • 19
  • 34
  • possible duplicate of [Calculating difference in dates in Java](http://stackoverflow.com/questions/453388/calculating-difference-in-dates-in-java) – jmj Dec 16 '10 at 10:51
  • 2
    You should not do calculations like that in JSP. do it in a backing java service bean and expose the values to the JSP. – Sean Patrick Floyd Dec 16 '10 at 10:58
  • Writing Java code incorrectly in a JSP file doesn't make it a JSP problem, you would have exactly the same problem when doing so in a normal Java class. So I removed the JSP tag. – BalusC Dec 16 '10 at 12:47

2 Answers2

1

I would recommend using joda time for this. It also factors the time zone and daylight saving differences. Here is an example of how to get difference of days between 2 dates.

Days d = Days.daysBetween(startDate, endDate);
int days = d.getDays();
if(days==15){
   //do something
}
CoolBeans
  • 20,654
  • 10
  • 86
  • 101
0

With the date4j library :

int days = dt.numDaysFrom(today);
John
  • 1,635
  • 15
  • 22