简体   繁体   中英

Finding difference between two dates

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.

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
}

使用date4j库:

int days = dt.numDaysFrom(today);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM