Home > Java > javaTutorial > body text

How to Add Days to a Date in Java?

Susan Sarandon
Release: 2024-11-13 14:58:02
Original
901 people have browsed it

How to Add Days to a Date in Java?

Adding Days to a Date in Java

The SimpleDateFormat class is a concrete implementation of the DateFormat class for formatting and parsing dates in a locale-sensitive manner. It allows the application to format date and time values consistently across different locales.

To add days to a date, we can use the add() method of the Calendar class. The add() method takes a field as the first parameter. The second parameter is the amount of the field to add to the calendar.

Here's an example of how to add 5 days to a date in Java:

SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
Calendar c = Calendar.getInstance();
c.setTime(new Date()); // Using today's date
c.add(Calendar.DATE, 5); // Adding 5 days
String output = sdf.format(c.getTime());
System.out.println(output);
Copy after login

In this example, we first create a SimpleDateFormat object. Then, we create a Calendar object and set it to the current date using the setTime() method. Next, we use the add() method to add 5 days to the calendar. Finally, we format the new date using the SimpleDateFormat object and print it out.

The above is the detailed content of How to Add Days to a Date in Java?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template