Java examples to add or subtract days, months or years from a given date using various date-time classes. If your requirement is to add or subtract only the business days then read the linked article.
1. Add or Subtract Days, Months, Years to Date since Java 8
This recommended approach if we are using JDK 1.8 or later.
New java.time classes LocalDate, LocalDateTime and ZonedDateTime have following plus methods to add days to a date.
- plusDays(long n) – adds
ndays to date. - plusWeeks(long n) – adds
nweeks to date. - plusMonths(long n) – adds
nmonths to date. - plusYears(long n) – adds
nyears to date.
Similarly, use the following minus methods to subtract days from a date.
- minusDays(long n) – subtracts
ndays from date. - minusWeeks(long n) – subtracts
nweeks from date. - minusMonths(long n) – subtracts
nmonths from date. - minusYears(long n) – subtracts
nyears from date.
Before returning the modified date, these methods modify the other date fields as well to ensure that the result date is a valid date.
These methods throw DateTimeException if the result exceeds the supported date range.
//1. Add and substract 1 day from LocalDate
LocalDate today = LocalDate.now(); //Today
LocalDate tomorrow = today.plusDays(1); //Plus 1 day
LocalDate yesterday = today.minusDays(1); //Minus 1 day
//2. Add and substract 1 month from LocalDateTime
LocalDateTime now = LocalDateTime.now(); //Current Date and Time
LocalDateTime sameDayNextMonth = now.plusMonths(1); //2018-08-14
LocalDateTime sameDayLastMonth = now.minusMonths(1); //2018-06-14
//3. Add and substract 1 year from LocalDateTime
LocalDateTime sameDayNextYear = now.plusYears(1); //2019-07-14
LocalDateTime sameDayLastYear = now.minusYears(1); //2017-07-14
2. Add or Subtract Days from java.util.Date
Till Java 7, the only good way to add days to Date was using Calendar class.
The calendar.add(int field, int amount) method takes two arguments, i.e., field type and the field value. We can use this method to add days, months or any time unit in the underlying Date class.
- To add a time unit, pass a positive number in the method.
- To subtract a time unit, pass a negative number in the method.
Date today = new Date();
System.out.println(today);
Calendar cal = Calendar.getInstance();
cal.setTime(today);
// Adding time
cal.add(Calendar.YEAR, 2);
cal.add(Calendar.MONTH, 2);
cal.add(Calendar.DATE, 2);
cal.add(Calendar.DAY_OF_MONTH, 2);
// Subtracting time
cal.add(Calendar.YEAR, -3);
cal.add(Calendar.MONTH, -3);
cal.add(Calendar.DATE, -3);
cal.add(Calendar.DAY_OF_MONTH, -3);
// convert calendar to date
Date modifiedDate = cal.getTime();
System.out.println(modifiedDate);
Happy Learning !!
Comments