Add Days To Date In Java example

Chapter: Date and Time Last Updated: 14-05-2023 05:38:25 UTC

Program:

            /* ............... START ............... */
                
import java.util.Calendar;

public class Main {
  public static void main(String[] args) {
    Calendar cal = Calendar.getInstance();
    cal.add(Calendar.DATE, 5);
    System.out.println("Date after adding 5 days: " + cal.getTime());
  }
}



/* Alternative method  */



import java.time.LocalDate;
import java.time.format.DateTimeFormatter;

public class DateExample {
    public static void main(String[] args) {
        // Get the current date
        LocalDate currentDate = LocalDate.now();
        System.out.println("Current date: " + formatDate(currentDate));

        // Add 5 days to the current date
        LocalDate futureDate = currentDate.plusDays(5);
        System.out.println("Date after adding 5 days: " + formatDate(futureDate));
    }

    private static String formatDate(LocalDate date) {
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        return date.format(formatter);
    }
}

                /* ............... END ............... */
        

Output

First Output
----------------
Date after adding 5 days: Sun May 19 09:27:03 GMT+04:00 2023

Second Output
Current date: 2023-05-14
Date after adding 5 days: 2023-05-19

Notes:

  • The Calendar class is used to perform this operation. First, we create an instance of the Calendar class using the getInstance() method.
  • Then, we use the add() method to add 5 days to the current date. Finally, we print out the new date using the getTime() method.
  • In second program , we start by obtaining the current date using LocalDate.now(). We then add 5 days to the current date using the plusDays() method. Finally, we format the dates using the DateTimeFormatter to display them in the desired format ("yyyy-MM-dd").
  • When you run this code, the output will show the current date and the date after adding 5 days. You can modify the number of days to add or customize the date format according to your requirements.

Tags

java add days to date, Add Days To Date In Java example, Java add days to date without Calendar

Similar Programs Chapter Last Updated
Java Date Format AM PM Date and Time 14-05-2023
Java Add Months To Date Date and Time 14-05-2023
Java Program To Calculate Days Between Two Dates Date and Time 16-04-2023
Java Program To Add Days To Date Date and Time 16-04-2023
How To Find Difference Between Two Dates In Java Date and Time 01-04-2023
Add Days To Date Java Example Date and Time 08-08-2021
Time Difference Between Two Timestamps In Java Date and Time 22-09-2018

1