Java add days to Date and LocalDateTime

Java examples to add or substract days, months or years from java.util.Date and java.time.LocalDateTime classes.

Java 8 Plus Minus Days to LocalDateTime

This recommended approach if you are using JDK 1.8 or later. New java.time classes i.e. LocalDate, LocalDateTime and ZoneDateTime have plus and minus methods, which can be used to add or substract time units from any time instant.

This is one approach where you can add days to Date without Calendar.

LocalDateTime today =  LocalDateTime.now();		//Today
LocalDateTime tomorrow = today.plusDays(1);		//Plus 1 day
LocalDateTime yesterday = today.minusDays(1);	//Minus 1 day

System.out.println(today);			//2018-07-14
System.out.println(tomorrow);		//2018-07-15
System.out.println(yesterday);		//2018-07-13

LocalDateTime sameDayNextMonth = today.plusMonths(1);		//2018-08-14
LocalDateTime sameDayLastMonth = today.minusMonths(1);		//2018-06-14

LocalDateTime sameDayNextYear = today.plusYears(1);		//2019-07-14
LocalDateTime sameDayLastYear = today.minusYears(1);	//2017-07-14

//Get Date from LocalDateTime 
//Not recommended. Use when you have no options in legacy code.
Date currentDatePlusOneDay = Date.from(tomorrow.atZone(ZoneId.systemDefault()).toInstant());

System.out.println(currentDatePlusOneDay);		//Sun Jul 15 22:25:04 IST 2018

Add days to Date [Java 7]

Till Java 7, only good way to add days to Date is using Calendar class. It’s calendar.add() method takes argument of various time units to manipulate the date. It can be used to add days, months or any time unit in underlying Date class.

Date today = new Date();
System.out.println(today);		//Sat Jul 14 22:25:03 IST 2018

Calendar cal = Calendar.getInstance();
cal.setTime(today);

// manipulate date
cal.add(Calendar.YEAR, 1);
cal.add(Calendar.MONTH, 1);
cal.add(Calendar.DATE, 1); 
cal.add(Calendar.DAY_OF_MONTH, 1);

// convert calendar to date
Date modifiedDate = cal.getTime();
System.out.println(modifiedDate);		//Fri Aug 16 22:25:03 IST 2019

Drop me your questions in comments section.

Happy Learning !!

References:

Date JavaDoc
Calendar JavaDoc
LocalDateTime JavaDoc

Was this post helpful?

Join 7000+ Fellow Programmers

Subscribe to get new post notifications, industry updates, best practices, and much more. Directly into your inbox, for free.

Leave a Comment

HowToDoInJava

A blog about Java and its related technologies, the best practices, algorithms, interview questions, scripting languages, and Python.