How to add days to a date in Java
Make use of Calendar#add()
. Here's a kickoff example.
Calendar dom = Calendar.getInstance();
dom.clear();
dom.set(y, m, d); // Note: month is zero based! Subtract with 1 if needed.
Calendar expire = (Calendar) dom.clone();
expire.add(Calendar.DATE, 100);
If you want more flexibility and less verbose code, I'd recommend JodaTime though.
DateTime dom = new DateTime(y, m, d, 0, 0, 0, 0);
DateTime expire = dom.plusDays(100);
java.time
Now, years later, the old java.util.Date/.Calendar classes are supplanted by the new java.time package in Java 8 and later.
These new classes include a LocalDate
class for representing a date-only without time-of-day nor time zone.
LocalDate localDate = LocalDate.of( 2015 , 2 , 3 ) ;
LocalDate later = localDate.plusDays( 100 );
That code above a works for dates. If you instead need to know exact moment of expiration, then you need time-of-day and time zones. In that case, use ZonedDateTime
class.
ZoneId zone = ZoneId.of( "America/Montreal" ) ;
ZonedDateTime zdt = later.atStartOfDay( zone ) ;
DateFormat formatter = null;
Date convertedDate = null;
formatter = new SimpleDateFormat("yyyy-MM-dd");
try {
convertedDate = (Date) formatter.parse(pro.getDate().toString());//pro.getDate() is the date getting from database
} catch (ParseException e) {
e.printStackTrace();
}
Calendar cal = Calendar.getInstance();
cal.setTime(convertedDate);
cal.add(Calendar.DATE, 7);
Date cvdate=cal.getTime();
if (cvdate.after(new Date())){
//do Something if you show expire...
}