616
votes

I'm working with a date in this format: yyyy-mm-dd.

How can I increment this date by one day?

30
If you are using Java 8 or newer you can use the new date/time api. See this answer: stackoverflow.com/a/23910924/1115554micha
new DateTime().plusDays(1).toDate() ???Pietro

30 Answers

725
votes

Something like this should do the trick:

String dt = "2008-01-01";  // Start date
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Calendar c = Calendar.getInstance();
c.setTime(sdf.parse(dt));
c.add(Calendar.DATE, 1);  // number of days to add
dt = sdf.format(c.getTime());  // dt is now the new date
229
votes

UPDATE (May 2021): This is a really outdated answer for old, old Java. For Java 8 and above, see https://stackoverflow.com/a/20906602/314283

Java does appear to be well behind the eight-ball compared to C#. This utility method shows the way to do in Java SE 6 using the Calendar.add method (presumably the only easy way).

public class DateUtil
{
    public static Date addDays(Date date, int days)
    {
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        cal.add(Calendar.DATE, days); //minus number would decrement the days
        return cal.getTime();
    }
}

To add one day, per the question asked, call it as follows:

String sourceDate = "2012-02-29";
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
Date myDate = format.parse(sourceDate);
myDate = DateUtil.addDays(myDate, 1);
94
votes

java.time

On Java 8 and later, the java.time package makes this pretty much automatic. (Tutorial)

Assuming String input and output:

import java.time.LocalDate;

public class DateIncrementer {
  static public String addOneDay(String date) {
    return LocalDate.parse(date).plusDays(1).toString();
  }
}
68
votes

I prefer to use DateUtils from Apache. Check this http://commons.apache.org/proper/commons-lang/javadocs/api-2.6/org/apache/commons/lang/time/DateUtils.html. It is handy especially when you have to use it multiple places in your project and would not want to write your one liner method for this.

The API says:

addDays(Date date, int amount) : Adds a number of days to a date returning a new object.

Note that it returns a new Date object and does not make changes to the previous one itself.

64
votes
SimpleDateFormat dateFormat = new SimpleDateFormat( "yyyy-MM-dd" );
Calendar cal = Calendar.getInstance();
cal.setTime( dateFormat.parse( inputString ) );
cal.add( Calendar.DATE, 1 );
52
votes

Construct a Calendar object and use the method add(Calendar.DATE, 1);

45
votes

Java 8 added a new API for working with dates and times.

With Java 8 you can use the following lines of code:

// parse date from yyyy-mm-dd pattern
LocalDate januaryFirst = LocalDate.parse("2014-01-01");

// add one day
LocalDate januarySecond = januaryFirst.plusDays(1);
44
votes

Take a look at Joda-Time (https://www.joda.org/joda-time/).

DateTimeFormatter parser = ISODateTimeFormat.date();

DateTime date = parser.parseDateTime(dateString);

String nextDay = parser.print(date.plusDays(1));
42
votes

Please note that this line adds 24 hours:

d1.getTime() + 1 * 24 * 60 * 60 * 1000

but this line adds one day

cal.add( Calendar.DATE, 1 );

On days with a daylight savings time change (25 or 23 hours) you will get different results!

32
votes

you can use Simple java.util lib

Calendar cal = Calendar.getInstance(); 
cal.setTime(yourDate); 
cal.add(Calendar.DATE, 1);
yourDate = cal.getTime();
25
votes
Date today = new Date();               
SimpleDateFormat formattedDate = new SimpleDateFormat("yyyyMMdd");            
Calendar c = Calendar.getInstance();        
c.add(Calendar.DATE, 1);  // number of days to add      
String tomorrow = (String)(formattedDate.format(c.getTime()));
System.out.println("Tomorrows date is " + tomorrow);

This will give tomorrow's date. c.add(...) parameters could be changed from 1 to another number for appropriate increment.

23
votes

If you are using Java 8, then do it like this.

LocalDate sourceDate = LocalDate.of(2017, Month.MAY, 27);  // Source Date
LocalDate destDate = sourceDate.plusDays(1); // Adding a day to source date.

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd"); // Setting date format

String destDate = destDate.format(formatter));  // End date

If you want to use SimpleDateFormat, then do it like this.

String sourceDate = "2017-05-27";  // Start date

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

Calendar calendar = Calendar.getInstance();
calendar.setTime(sdf.parse(sourceDate)); // parsed date and setting to calendar

calendar.add(Calendar.DATE, 1);  // number of days to add
String destDate = sdf.format(calendar.getTime());  // End date
17
votes
long timeadj = 24*60*60*1000;
Date newDate = new Date (oldDate.getTime ()+timeadj);

This takes the number of milliseconds since epoch from oldDate and adds 1 day worth of milliseconds then uses the Date() public constructor to create a date using the new value. This method allows you to add 1 day, or any number of hours/minutes, not only whole days.

17
votes

Since Java 1.5 TimeUnit.DAYS.toMillis(1) looks more clean to me.

SimpleDateFormat dateFormat = new SimpleDateFormat( "yyyy-MM-dd" );
Date day = dateFormat.parse(string);
// add the day
Date dayAfter = new Date(day.getTime() + TimeUnit.DAYS.toMillis(1));
16
votes

In Java 8 simple way to do is:

Date.from(Instant.now().plusSeconds(SECONDS_PER_DAY))
13
votes

It's very simple, trying to explain in a simple word. get the today's date as below

Calendar calendar = Calendar.getInstance();
System.out.println(calendar.getTime());// print today's date
calendar.add(Calendar.DATE, 1);

Now set one day ahead with this date by calendar.add method which takes (constant, value). Here constant could be DATE, hours, min, sec etc. and value is the value of constant. Like for one day, ahead constant is Calendar.DATE and its value are 1 because we want one day ahead value.

System.out.println(calendar.getTime());// print modified date which is tomorrow's date

Thanks

12
votes
startCalendar.add(Calendar.DATE, 1); //Add 1 Day to the current Calender
11
votes

In java 8 you can use java.time.LocalDate

LocalDate parsedDate = LocalDate.parse("2015-10-30"); //Parse date from String
LocalDate addedDate = parsedDate.plusDays(1);   //Add one to the day field

You can convert in into java.util.Date object as follows.

Date date = Date.from(addedDate.atStartOfDay(ZoneId.systemDefault()).toInstant());

You can formate LocalDate into a String as follows.

String str = addedDate.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
9
votes

With Java SE 8 or higher you should use the new Date/Time API

 int days = 7;       
 LocalDate dateRedeemed = LocalDate.now();
 DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd/MM/YYYY");

 String newDate = dateRedeemed.plusDays(days).format(formatter);   
 System.out.println(newDate);

If you need to convert from java.util.Date to java.time.LocalDate, you may use this method.

  public LocalDate asLocalDate(Date date) {
      Instant instant = date.toInstant();
      ZonedDateTime zdt = instant.atZone(ZoneId.systemDefault());
      return zdt.toLocalDate();
  }

With a version prior to Java SE 8 you may use Joda-Time

Joda-Time provides a quality replacement for the Java date and time classes and is the de facto standard date and time library for Java prior to Java SE 8

   int days = 7;       
   DateTime dateRedeemed = DateTime.now();
   DateTimeFormatter formatter = DateTimeFormat.forPattern("dd/MM/uuuu");
        
   String newDate = dateRedeemed.plusDays(days).toString(formatter);   
   System.out.println(newDate);
7
votes

Apache Commons already has this DateUtils.addDays(Date date, int amount) http://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/time/DateUtils.html#addDays%28java.util.Date,%20int%29 which you use or you could go with the JodaTime to make it more cleaner.

7
votes

Just pass date in String and number of next days

 private String getNextDate(String givenDate,int noOfDays) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        Calendar cal = Calendar.getInstance();
        String nextDaysDate = null;
    try {
        cal.setTime(dateFormat.parse(givenDate));
        cal.add(Calendar.DATE, noOfDays);

       nextDaysDate = dateFormat.format(cal.getTime());

    } catch (ParseException ex) {
        Logger.getLogger(GR_TravelRepublic.class.getName()).log(Level.SEVERE, null, ex);
    }finally{
    dateFormat = null;
    cal = null;
    }

    return nextDaysDate;

}
7
votes

If you want to add a single unit of time and you expect that other fields to be incremented as well, you can safely use add method. See example below:

SimpleDateFormat simpleDateFormat1 = new SimpleDateFormat("yyyy-MM-dd");
Calendar cal = Calendar.getInstance();
cal.set(1970,Calendar.DECEMBER,31);
System.out.println(simpleDateFormat1.format(cal.getTime()));
cal.add(Calendar.DATE, 1);
System.out.println(simpleDateFormat1.format(cal.getTime()));
cal.add(Calendar.DATE, -1);
System.out.println(simpleDateFormat1.format(cal.getTime()));

Will Print:

1970-12-31
1971-01-01
1970-12-31
5
votes

Use the DateFormat API to convert the String into a Date object, then use the Calendar API to add one day. Let me know if you want specific code examples, and I can update my answer.

5
votes

It's simple actually. One day contains 86400000 milliSeconds. So first you get the current time in millis from The System by usingSystem.currentTimeMillis() then add the 84000000 milliSeconds and use the Date Class to generate A date format for the milliseconds.

Example

String Today = new Date(System.currentTimeMillis()).toString();

String Today will be 2019-05-9

String Tommorow = new Date(System.currentTimeMillis() + 86400000).toString();

String Tommorow will be 2019-05-10

String DayAfterTommorow = new Date(System.currentTimeMillis() + (2 * 86400000)).toString();

String DayAfterTommorow will be 2019-05-11

4
votes

You can use this package from "org.apache.commons.lang3.time":

 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
 Date myNewDate = DateUtils.addDays(myDate, 4);
 Date yesterday = DateUtils.addDays(myDate, -1);
 String formatedDate = sdf.format(myNewDate);  
3
votes

If you are using Java 8, java.time.LocalDate and java.time.format.DateTimeFormatter can make this work quite simple.

public String nextDate(String date){
      LocalDate parsedDate = LocalDate.parse(date);
      LocalDate addedDate = parsedDate.plusDays(1);
      DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-mm-dd");
      return addedDate.format(formatter); 
}
3
votes

Try this method:

public static Date addDay(int day) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        calendar.add(Calendar.DATE, day);
        return calendar.getTime();
}
2
votes

Let's clarify the use case: You want to do calendar arithmetic and start/end with a java.util.Date.

Some approaches:

  1. Convert to string and back with SimpleDateFormat: This is an inefficient solution.
  2. Convert to LocalDate: You would lose any time-of-day information.
  3. Convert to LocalDateTime: This involves more steps and you need to worry about timezone.
  4. Convert to epoch with Date.getTime(): This is efficient but you are calculating with milliseconds.

Consider using java.time.Instant:

Date _now = new Date();
Instant _instant = _now.toInstant().minus(5, ChronoUnit.DAYS);
Date _newDate = Date.from(_instant);
0
votes
Date newDate = new Date();
newDate.setDate(newDate.getDate()+1);
System.out.println(newDate);
0
votes

I think the fastest one, that never will be deprecated, it's the one that go to the core

let d=new Date();
d.setTime(d.getTime()+86400000);
console.log(d);

It's just one line, and just 2 commands. It works on Date type, without using calendar.

I always think it's better to work with unix times on code side, and present the date just when it's ready to be shown to the user.

To print a date d, I use

let format1 = new Intl.DateTimeFormat('en', { year: 'numeric', month: 'numeric', month: '2-digit', day: '2-digit'});
let [{ value: month },,{ value: day },,{ value: year }] = format1.formatToParts(d);

It sets vars month year and day but can be extended to hours minutes and seconds and can be used also in standard rapresentations depending on country flag.