Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add days to a date in Java

Tags:

java

date

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.

like image 509
terrific Avatar asked Dec 17 '22 02:12

terrific


2 Answers

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);
like image 192
BalusC Avatar answered Dec 19 '22 15:12

BalusC


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 ) ;
like image 37
Basil Bourque Avatar answered Dec 19 '22 14:12

Basil Bourque