Java 8 ExamplesJava8

How to add a number of days to a Date in Java

Posted On
Posted By admin

In this article, I will be demonstrating how to add a number of days to a Date in Java

Before Java 8

Prior to Java 8, the Date and Calendar classes were available for Date manipulation. They make operations like adding a number of days to a Date very difficult. The following code demonstrates adding days to a date using the Calendar class:

String stringDate="2019-07-15";  
Date date1=new SimpleDateFormat("yyyy-MM-dd").parse(stringDate);  
Calendar cal = Calendar.getInstance();
cal.setTime(date1);
    
// manipulate date
cal.add(Calendar.DATE, 5); 
Date dateWith5Days = cal.getTime();
    
System.out.println(dateWith5Days);

So the above code first uses SimpleDateFormat.parse to convert a String date to a java.util.Date. It then creates a Calendar object corresponding to this date. Finally, it uses the Calendar.add method to add days to the date.

Using Java 8

Java 8 introduced the LocalDate class which makes date manipulations like adding/subtracting days/months very easy. The following code demonstrates this:

LocalDate date = LocalDate.parse("2019-07-15");
    
//add 5 days
LocalDate date2 = date.plusDays(5);
System.out.println("Date "+date+" plus 5 days is "+date2);

So this code first creates a LocalDate object corresponding to the String date. It then invokes the plusDays method to add 5 days to the specified date.

Not only days, the LocalDate class the several methods that allow you to add/subtract months, years from the LocalDate object.

Conclusion

 

If you'd like to watch a detailed video tutorial of this topic or other related topics, do check out my new course Learn Java 8 New Features

If you like this post, please do let me know via the comments box below.  You can also connect with me via my Facebook Page or subscribe to my Youtube channel!

Related Post

leave a Comment