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 expiry 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);
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 ) ;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With