-1

Can any one help me with the code for adding some number of days to any date..?

For example today is 11-04-2014. I want 15-04-2014 + 3 days output:18-04-2014.

My question is not adding dates to current date..

Gabe Sechan
  • 90,003
  • 9
  • 87
  • 127

4 Answers4

2

With Java 8, you can write:

import java.time.LocalDate;

LocalDate date = LocalDate.of(2014, 4, 11);
LocalDate newDate = date.plusDays(3);
System.out.println(newDate); //  Prints 2014-04-14

Its that simple.

Aman Agnihotri
  • 2,973
  • 1
  • 18
  • 22
  • This is the best Answer, using the modern java.time classes rather than the troublesome old legacy date-time classes `Calendar` & `Date`. – Basil Bourque Oct 02 '17 at 05:21
1
String dateString = "11-04-2014" // Say you have a date in String format
SimpleDateFormat format = new SimpleDateFormat("MM-dd-yyyy"); // Create an instance of SimpleDateFormat with the right format.
Date date = format.parse(dateString); // Then parse the string, this will need a try catch statement.
Calendar calendar = Calendar.getInstance(); // Get an instance of the calendar.
calendar.setTime(date); // Set the time of the calendar to the parsed date
calendar.add(Calendar.DATE, 3); // Add the days to the calendar
String outputFormat = format.format(calendar.getTime());
Tamby Kojak
  • 2,129
  • 1
  • 14
  • 25
0
import java.util.Calendar;
import java.text.SimpleDateFormat;

public class A {
    public static void main(String[] args) {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd/MM/yyyy");

        Calendar calendar = Calendar.getInstance();    
        calendar.set(Calendar.DAY_OF_MONTH, 1);
        calendar.set(Calendar.MONTH, 1);
        calendar.set(Calendar.YEAR, 2012);
        calendar.add(Calendar.DAY_OF_MONTH, 3);

        System.out.println(simpleDateFormat.format(calendar.getTime()));
    }
}
Mdev
  • 2,440
  • 2
  • 17
  • 25
0

You can use the calendar function:

Calendar cal = Calendar.getInstance();
cal.setTime(dateInstance);
cal.add(Calendar.DATE, NO_OF_DAYS_TO_ADD);
Date addedDays = cal.getTime();

DateInstance is the date you are using. addedDays can be formatted using SimpleDateFormat to display in any date format that you would like to use.

ngrashia
  • 9,869
  • 5
  • 43
  • 58