How to Add Days to a Date in Java

Jan 13, 2024

2 mins read

Published in

Here is the code for How to add days to date in java

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

public class DateAddition {
    public static void main(String[] args) {
        try {
            // Input date in string format
            String inputDate = "2022-01-13";
            // Number of days to add
            int daysToAdd = 7;

            // Parsing the input date string to a Date object
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            Date date = sdf.parse(inputDate);

            // Creating a Calendar instance and setting it to the input date
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(date);

            // Adding days to the date
            calendar.add(Calendar.DAY_OF_MONTH, daysToAdd);

            // Getting the updated date
            Date updatedDate = calendar.getTime();

            // Displaying the result
            System.out.println("Original Date: " + sdf.format(date));
            System.out.println("Date after adding " + daysToAdd + " days: " + sdf.format(updatedDate));

        } catch (ParseException e) {
            e.printStackTrace();
        }
    }
}

Explanation:

  1. Import Necessary Classes: Import the required classes for date manipulation.

  2. Define the Main Class and Method: Create a class with a main method to execute the date addition.

  3. Input Date and Days to Add: Specify the input date as a string and the number of days to add.

  4. Parse Input Date: Use SimpleDateFormat to parse the input date string into a Date object.

  5. Create Calendar Instance: Create a Calendar instance and set it to the parsed date.

  6. Add Days to Date: Use the add method of Calendar to add the specified number of days.

  7. Get Updated Date: Retrieve the updated date from the Calendar instance.

  8. Display Result: Print the original date and the date after adding the specified days.

Sharing is caring!