Wednesday, February 20, 2013

How to compare two Dates ?


Use Case : How to compare two java.util.Date values ?
Implementation :

// Below method adds number of days to the given date based on provided time zone and return the result Date value


    public static Date addDays(Date pDate, int pDays, TimeZone pTimeZone) {

        Calendar cal = Calendar.getInstance();
        cal.setTime(pDate);
        cal.add(Calendar.DAY_OF_MONTH, pDays);
        cal.setTimeZone(pTimeZone);
        return cal.getTime();
    }


    public static boolean before(Date pFromDate, Date pToDate) {
        return pFromDate.before(pToDate);
    }






// Compare the date

Date date1 = new Date() // Current Date
Date date2 = addDays(date1,365,Timezone.getDefaultTimezone()); // 1 year from now
Date endDate // User entered data

boolean result = before(date2,endDate); // true - if date2 is before end date otherwise false.






No comments:

Post a Comment