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.

3
  • possible duplicate of Calculating difference in dates in Java Commented Dec 16, 2010 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. Commented Dec 16, 2010 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. Commented Dec 16, 2010 at 12:47

2 Answers 2

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
}
Sign up to request clarification or add additional context in comments.

Comments

0

With the date4j library :

int days = dt.numDaysFrom(today);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.