I want to add days to a date to get a new date in Java. How to achieve it using the Calendar
class.
Calendar dom = new GregorianCalendar(d, m, y);
is the instance of my date of manufacture and I want to reach to date of expir开发者_JAVA技巧y adding some 100 days to the current date and store it in a variable doe
but unable to do that.
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...
}
精彩评论