661

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

How can I increment this date by one day?

Matthias Braun
  • 32,039
  • 22
  • 142
  • 171
user48094
  • 10,481
  • 12
  • 36
  • 30

32 Answers32

753

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
Sam Hasler
  • 12,344
  • 10
  • 72
  • 106
Dave
  • 7,788
  • 1
  • 15
  • 5
  • 2
    c.roll(Calendar.DATE, true); would be somewhat better for clarity. – Esko Jan 09 '09 at 19:25
  • 53
    @Esko, c.roll(Calendar.DATE, true) won't roll the month on the last day of the month. – Sam Hasler Jul 31 '09 at 22:38
  • 14
    I'll quote some JavaDocs... Calendar.DATE: "...This is a synonym for DAY_OF_MONTH." I wish the JavaDocs would clarify that this would increment larger fields (like the month and year). Calendar.roll "Adds or subtracts (up/down) a single unit of time on the given time field without changing larger fields" .. Again, "larger fields" is vague but that seems consistent with Sam's comment. I wish there were a StackOverflow for fixing old the JavaDocs. – jcalfee314 Aug 30 '12 at 12:06
  • Note that now many `Date` methods are deprecated, and `Calendar` should be use instead of `Date` anyway. – Tyzoid May 24 '13 at 13:45
  • `"yyyy-MM-dd"` Observe - month has to be in uppercase. `"mm"` would give minutes :). – anujin Oct 31 '13 at 08:35
  • 4
    guys, unfortunately, it's quite useless to add days using DATE, DAY_OF_MONTH or even DAY_OF_YEAR - they all are incremented by modulus. So considering Calendar of 31-12-1970, add(DAY_OF_YEAR, 1) or roll(), however roll() finally calls add(), will give 01-01-1970. I guess the only correct way is to set time with milliseconds. As for me, I'm never using Calendar class again. – Dmitry Gryazin Sep 17 '14 at 14:38
  • 15
    @Bagzerg: You are **wrong**. `add()` will roll the date. See on [ideone](http://ideone.com/YQp7rp). – Jean Hominal Feb 09 '15 at 14:14
  • 1
    I'd add one important thing: Make sure that the timezone of SimpleDateFormat and Calendar are the same. I was inadvertently using UTC as the timezone of the SimpleDateFormat, but was using a local timezone for the Calendar object. UTC doesn't observe daylight saving time, but my local time zone does. So, when I incremented the calendar 1 day in the Spring when we "lose" an hour, UTC recorded it as only gaining 23 hours -- and therefore on the same day. Thus the above algorithm uses the same day "2012-03-11" twice. The opposite happens in the Fall, and day "2012-11-04" would be skipped. – user64141 May 14 '15 at 15:21
  • @SamHasler If i am adding 1 day to the last day of month, the month remains same instead of moving to next month, how to make that work ? – Derrick Jan 29 '18 at 12:55
  • 4
    FYI, the terribly troublesome old date-time classes such as [`java.util.Date`](https://docs.oracle.com/javase/10/docs/api/java/util/Date.html), [`java.util.Calendar`](https://docs.oracle.com/javase/10/docs/api/java/util/Calendar.html), and `java.text.SimpleDateFormat` are now [legacy](https://en.wikipedia.org/wiki/Legacy_system), supplanted by the [*java.time*](https://docs.oracle.com/javase/10/docs/api/java/time/package-summary.html) classes built into Java 8 and later. See [*Tutorial* by Oracle](https://docs.oracle.com/javase/tutorial/datetime/TOC.html). – Basil Bourque Jul 31 '18 at 07:29
  • @SamHasler I need date need to format in DDMMM - when I used the below code I see Date as 08JAN instead of 08JUN , can someone help? `String dt = "07JUN"; // Start date SimpleDateFormat sdf = new SimpleDateFormat("DDMMM"); Calendar c = Calendar.getInstance(); c.setTime(sdf.parse(dt)); c.add(Calendar.DATE, 1); c.roll(Calendar.DATE, true); dt = sdf.format(c.getTime()); ` – Lokesh Reddy Jun 07 '22 at 10:30
  • @LokeshReddy not my answer, I only edited it. You're right though: https://www.online-java.com/jTnRcCApzq I can't understand why though: https://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html – Sam Hasler Jun 08 '22 at 16:00
254

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);
Lisa
  • 4,333
  • 2
  • 27
  • 34
  • 8
    FYI, the terribly troublesome old date-time classes such as [`java.util.Date`](https://docs.oracle.com/javase/10/docs/api/java/util/Date.html), [`java.util.Calendar`](https://docs.oracle.com/javase/10/docs/api/java/util/Calendar.html), and `java.text.SimpleDateFormat` are now [legacy](https://en.wikipedia.org/wiki/Legacy_system), supplanted by the [*java.time*](https://docs.oracle.com/javase/10/docs/api/java/time/package-summary.html) classes built into Java 8 and later. See [*Tutorial* by Oracle](https://docs.oracle.com/javase/tutorial/datetime/TOC.html). – Basil Bourque Jul 31 '18 at 07:30
105

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();
  }
}
Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
Daniel C. Sobral
  • 295,120
  • 86
  • 501
  • 681
  • 8
    FYI, both [`ZonedDateDateTime`](https://docs.oracle.com/javase/8/docs/api/java/time/ZonedDateTime.html) and [`OffsetDateTime`](https://docs.oracle.com/javase/8/docs/api/java/time/OffsetDateTime.html) also have `plusDays` and `minusDays` methods as well as `LocalDate` – Basil Bourque Mar 16 '16 at 16:48
  • @BasilBourque Sure, but the information available in the question is that of a `LocalDate`. – Daniel C. Sobral Mar 16 '16 at 19:12
  • 4
    @DanielCSobral Yep. Just adding links for your readers’ edification. Not a criticism. – Basil Bourque Mar 16 '16 at 21:34
72

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.

Edward Anderson
  • 13,591
  • 4
  • 52
  • 48
Risav Karna
  • 936
  • 8
  • 16
69
SimpleDateFormat dateFormat = new SimpleDateFormat( "yyyy-MM-dd" );
Calendar cal = Calendar.getInstance();
cal.setTime( dateFormat.parse( inputString ) );
cal.add( Calendar.DATE, 1 );
Alex B
  • 24,678
  • 14
  • 64
  • 87
57

Construct a Calendar object and call add(Calendar.DATE, 1);

Neuron
  • 5,141
  • 5
  • 38
  • 59
krosenvold
  • 75,535
  • 32
  • 152
  • 208
47

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);
micha
  • 47,774
  • 16
  • 73
  • 80
  • 2
    I guess you meant `januaryFirst.plusDays(1)` not `date.plusDays(1)`. – TeWu Sep 11 '16 at 09:46
  • This is only supported on android O https://developer.android.com/reference/java/time/package-summary.html – Subho May 18 '17 at 08:20
  • 2
    @Subho For Android before 26, see the *ThreeTenABP* project that adapts the *ThreeTen-Backport* project, a back-port if most of the *java-time* functionality to Java 6 and Java 7. – Basil Bourque Jul 29 '18 at 20:24
45

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));
JodaStephen
  • 60,927
  • 15
  • 95
  • 117
DaWilli
  • 4,808
  • 1
  • 16
  • 7
  • 4
    You can remove the parser calls for constructing the DateTime. Use DateTime date = new DateTime(dateString); Then, nextDay is ISODateTimeFormat.date().print(date.plusDays(1)); See http://joda-time.sourceforge.net/api-release/org/joda/time/DateTime.html#DateTime(java.lang.Object) for more info. – MetroidFan2002 Jan 10 '09 at 06:33
  • For more detailed example code using Joda-Time, see [my answer](http://stackoverflow.com/a/20061066/642706) to a similar question, [How to add one day to a date?](http://stackoverflow.com/q/1005523/642706). – Basil Bourque Nov 19 '13 at 00:57
  • 3
    FYI… The Joda-Time project is now in maintenance-mode, and advises migration to the *java.time* classes. Both efforts were led by the same man, Stephen Colebourne. So they share similar concepts, and migration is not difficult. – Basil Bourque Jul 29 '18 at 20:14
44

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!

Florian R.
  • 441
  • 4
  • 2
35

you can use Simple java.util lib

Calendar cal = Calendar.getInstance(); 
cal.setTime(yourDate); 
cal.add(Calendar.DATE, 1);
yourDate = cal.getTime();
Pawan Pareek
  • 469
  • 4
  • 7
  • 3
    This Answer duplicates the content of multiple Answers including [the accepted Answer](http://stackoverflow.com/a/428966/642706) from three years ago. Please delete your Answer or edit to add value. – Basil Bourque Jun 30 '15 at 17:28
  • 5
    this answer is cleaner, doesnt parse the date in the middle. the "accepted answer" is too convoluted. it's good you added yours, disregard basil's automated remark – Mickey Perlstein Nov 30 '17 at 13:19
  • FYI, the terribly troublesome old date-time classes such as [`java.util.Date`](https://docs.oracle.com/javase/10/docs/api/java/util/Date.html), [`java.util.Calendar`](https://docs.oracle.com/javase/10/docs/api/java/util/Calendar.html), and `java.text.SimpleDateFormat` are now [legacy](https://en.wikipedia.org/wiki/Legacy_system), supplanted by the [*java.time*](https://docs.oracle.com/javase/10/docs/api/java/time/package-summary.html) classes built into Java 8 and later. See [*Tutorial* by Oracle](https://docs.oracle.com/javase/tutorial/datetime/TOC.html). – Basil Bourque Nov 27 '18 at 20:29
  • Best answer, straight to the point. I agree with Mickey, just disregard basil's comment – eramirez75 Mar 27 '20 at 20:16
26
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.

Rey
  • 3,663
  • 3
  • 32
  • 55
Akhilesh T.
  • 261
  • 3
  • 2
  • 2
    you can do something like c.setTime(Date object) to set a specific Date before adding. – Linh Lino Jun 05 '14 at 21:24
  • I wish the default java packages would make handling dates less convoluted... I mean it's such a pain every time you want to deal with dates... just a rant... – Shane Sepac Dec 23 '17 at 18:12
  • 2
    @Shn_Android_Dev The *java.time* classes built into Java 8 and later supplant the terrible old date-time classes, and answer your wish. Also back-ported to Java 6/7 & earlier Android in the *ThreeTen-Backport* and *ThreeTenABP* projects. No need to ever use `Date` or `Calendar` again. – Basil Bourque Jul 29 '18 at 20:22
24

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
Avijit Karmakar
  • 8,890
  • 6
  • 44
  • 59
  • No, the Question asked for a date-only value not a date-time. So use the `LocalDate` class not `LocalDateTime`. – Basil Bourque May 27 '17 at 06:31
  • 2
    Your Answer repeats the content of at least four other Answers. Please explain how yours adds value beyond those, or else delete before you collect down-votes. – Basil Bourque May 27 '17 at 06:39
23

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));
Jens
  • 1,599
  • 14
  • 33
  • This creates a date-time value where the Question asks for a date-only. I suggest a much wiser approach is the [`LocalDate`](https://docs.oracle.com/javase/8/docs/api/java/time/LocalDate.html) class in the java.time classes for Java 8 and later, and the back-port to Java 6 & Java 7 found in the [ThreeTen-Backport](http://www.threeten.org/threetenbp/) project. – Basil Bourque Feb 24 '17 at 22:10
18
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.

dvaey
  • 300
  • 4
  • 5
  • This is probably not what OP wanted; it doesn't make any allowance for Daylight Savings-type adjustments, leap seconds and so on. – mrec Sep 18 '14 at 17:08
  • 1
    Daylight savings should be handled by timezone/locale. My example was showing how to increment by small durations. When incrementing by days, leap seconds can be an issue but when adding hours, it is less likely although still possible. – dvaey Sep 19 '14 at 00:15
17

In Java 8 simple way to do is:

Date.from(Instant.now().plusSeconds(SECONDS_PER_DAY))
dpk
  • 641
  • 1
  • 5
  • 15
  • 19
    Seems a bit of a stretch. Why not just go with [`Instant.now().plus( 1 , ChronoUnit.DAYS )`](https://docs.oracle.com/javase/10/docs/api/java/time/Instant.html#plus(long,java.time.temporal.TemporalUnit)) ? – Basil Bourque Jul 31 '18 at 07:28
14

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

Yoon5oo
  • 496
  • 5
  • 11
Kushwaha
  • 850
  • 10
  • 13
13
startCalendar.add(Calendar.DATE, 1); //Add 1 Day to the current Calender
Abdurahman Popal
  • 2,859
  • 24
  • 18
  • 6
    Thank you for wanting to contribute. However this is already in several of the other answers, so I really see no point… Apart from that IMHO nobody should use the poorly designed and long outdated `Calendar` class in 2019. – Ole V.V. Feb 18 '19 at 09:19
  • 1
    it's better to use synonym constant `Calendar.DAY_OF_MONTH` for code readability – user924 Apr 11 '21 at 14:39
11

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"));
Ramesh-X
  • 4,853
  • 6
  • 46
  • 67
10

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);
eHayik
  • 2,981
  • 1
  • 21
  • 33
7

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.

ROCKY
  • 1,763
  • 1
  • 21
  • 25
7

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;

}
LMK
  • 2,882
  • 5
  • 28
  • 52
7

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
terrmith
  • 113
  • 1
  • 8
  • There is no accepted answer and I felt there was overall confusion if other fields are updated aswell. – terrmith Feb 10 '15 at 08:58
6

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.

Ross
  • 9,652
  • 8
  • 35
  • 35
6

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();
}
Z4n3tti
  • 115
  • 3
  • 13
  • It looks correct, but the `Calendar` and `Date` classes are poorly designed and long outdated, so this is not the recommended way. Prefer `LocalDate.now(ZoneId.systemDefault()).plusDays(day)`. Also I can’t see you’re contributing anything essential that isn’t already in the second highest voted answer by Lisa. – Ole V.V. Jan 15 '21 at 14:38
  • Hello, I totally agree with you, but I have not seen the second highest voted answer before publishing mine. – Z4n3tti Jan 18 '21 at 10:02
  • it's better to use synonym constant `Calendar.DAY_OF_MONTH` for code readability – user924 Apr 11 '21 at 14:39
5

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

Mike T
  • 115
  • 2
  • 6
  • 2
    This code uses the terrible `Date` class that was supplanted years ago by the modern *java.time* classes. So much simpler to simply use: `LocalDate.parse( "2019-01-23" ).plusDays( 1 )` – Basil Bourque May 09 '19 at 15:31
4

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);  
JonathanDavidArndt
  • 2,518
  • 13
  • 37
  • 49
Shaheed
  • 92
  • 4
  • 6
    Suggesting `Date` class in 2018 is poor advice. The troublesome old date-time classes such as [`java.util.Date`](https://docs.oracle.com/javase/9/docs/api/java/util/Date.html), `java.util.Calendar`, and `java.text.SimpleDateFormat` are now [legacy](https://en.wikipedia.org/wiki/Legacy_system), supplanted by the [java.time](https://docs.oracle.com/javase/9/docs/api/java/time/package-summary.html) classes built into Java 8 & Java 9. See [*Tutorial* by Oracle](https://docs.oracle.com/javase/tutorial/datetime/TOC.html). See other Answers using `LocalDate` class. – Basil Bourque Feb 27 '18 at 19:55
  • Yes it is, LocalDate IS the best way to do that, – Shaheed Feb 28 '18 at 20:06
  • however some frameworks like jsf have a little integration problems with time API so sometimes you should use Date; plus environment java < 8 – Lucke Jul 27 '18 at 08:01
  • 1
    @Lucke Most of the *java.time* functionality was back-ported to Java 6 & 7 in the *ThreeTen-Backport* project. Further adapted to older Android in *ThreeTenABP* project. So, really no need to ever touch those bloody awful old date-time classes. Many frameworks have been updated. But not all. So if you must interoperate with old code not yet updated to *java.time*, write your new code in *java.time* and convert to/from the old types by calling new conversion methods added to the old classes. – Basil Bourque Jul 29 '18 at 20:28
  • 1
    This code ignores the **crucial issue of time zone**. For any given moment, the date varies around the glob by zone. The `SimpleDateFormat` class unfortunately injects a time zone, implicitly applying the JVM’s current default zone. So the results of this code will vary by whatever the current default is — and that default can change at any moment *during* runtime. – Basil Bourque Nov 27 '18 at 20:28
3

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); 
}
realhu
  • 935
  • 9
  • 12
  • Even simpler: Drop the formatter and just use `toString()` to produce the string i yyyy-MM-dd format (and if you insist, remember that `mm` is minutes while `MM` is the month). – Ole V.V. Apr 14 '17 at 10:49
3

The highest voted answer uses legacy java.util date-time API which was the correct thing to do in 2009 when the question was asked. In March 2014, java.time API supplanted the error-prone legacy date-time API. Since then, it is strongly recommended to use this modern date-time API.

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

You have used the wrong letter for the month, irrespective of whether you are using the legacy parsing/formatting API or the modern one. The letter m is used for minute-of-hour and the correct letter for month-of-year is M.

yyyy-MM-dd is the default format of java.time.LocalDate

The java.time API is based on ISO 8601 standards and therefore it does not require specifying a DateTimeFormatter explicitly to parse a date-time string if it is already in ISO 8601 format. Similarly, the toString implementation of a java.time type returns a string in ISO 8601 format. Check LocalDate#parse and LocalDate#toString for more information.

Ways to increment a local date by one day

There are three options:

  1. LocalDate#plusDays(long daysToAdd)
  2. LocalDate#plus(long amountToAdd, TemporalUnit unit): It has got some additional capabilities e.g. you can use it to increment a local date by days, weeks, months, years etc.
  3. LocalDate#plus(TemporalAmount amountToAdd): You can specify a Period (or any other type implementing the TemporalAmount) to add.

Demo:

import java.time.Instant;
import java.time.LocalDate;
import java.time.Period;
import java.time.temporal.ChronoUnit;

public class Main {
    public static void main(String[] args) {
        // Parsing
        LocalDate ldt = LocalDate.parse("2020-10-20");
        System.out.println(ldt);

        // Incrementing by one day
        LocalDate oneDayLater = ldt.plusDays(1);
        System.out.println(oneDayLater);

        // Alternatively
        oneDayLater = ldt.plus(1, ChronoUnit.DAYS);
        System.out.println(oneDayLater);

        oneDayLater = ldt.plus(Period.ofDays(1));
        System.out.println(oneDayLater);

        String desiredString = oneDayLater.toString();
        System.out.println(desiredString);
    }
}

Output:

2020-10-20
2020-10-21
2020-10-21
2020-10-21
2020-10-21

How to switch from the legacy to the modern date-time API?

You can switch from the legacy to the modern date-time API using Date#toInstant on a java-util-date instance. Once you have an Instant, you can easily obtain other date-time types of java.time API. An Instant represents a moment in time and is independent of a time-zone i.e. it represents a date-time in UTC (often displayed as Z which stands for Zulu-time and has a ZoneOffset of +00:00).

Demo:

import java.time.Instant;
import java.time.LocalDateTime;
import java.time.OffsetDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.time.ZonedDateTime;
import java.util.Date;

public class Main {
    public static void main(String[] args) {
        Date date = new Date();
        Instant instant = date.toInstant();
        System.out.println(instant);

        ZonedDateTime zdt = instant.atZone(ZoneId.of("Asia/Kolkata"));
        System.out.println(zdt);

        OffsetDateTime odt = instant.atOffset(ZoneOffset.of("+05:30"));
        System.out.println(odt);
        // Alternatively, using time-zone
        odt = instant.atZone(ZoneId.of("Asia/Kolkata")).toOffsetDateTime();
        System.out.println(odt);

        LocalDateTime ldt = LocalDateTime.ofInstant(instant, ZoneId.of("Asia/Kolkata"));
        System.out.println(ldt);
        // Alternatively,
        ldt = instant.atZone(ZoneId.of("Asia/Kolkata")).toLocalDateTime();
        System.out.println(ldt);
    }
}

Output:

2022-11-12T12:52:18.016Z
2022-11-12T18:22:18.016+05:30[Asia/Kolkata]
2022-11-12T18:22:18.016+05:30
2022-11-12T18:22:18.016+05:30
2022-11-12T18:22:18.016
2022-11-12T18:22:18.016

Learn more about the modern Date-Time API from Trail: Date Time.

Arvind Kumar Avinash
  • 71,965
  • 6
  • 74
  • 110
2

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);
Chad Juliano
  • 1,195
  • 9
  • 4
  • 1
    Never mix the terrible legacy classes such as `Date` with the modern *java.time* classes such as `Instant`. The *java.time* classes entirely supplant the legacy classes. Specifically, `Instant` replaces `java.util.Date`. – Basil Bourque Nov 27 '18 at 20:21
  • 1
    **Does not address the Question.** You are using classes representing a moment (a date with time-of-day in context of an offset or zone). But the Question asks about date-only without time-of-day and without time zone. See [correct Answer](https://stackoverflow.com/a/20906602/642706) by Sobral and [correct Answer](https://stackoverflow.com/a/23910924/642706) by micha. – Basil Bourque Nov 27 '18 at 20:25
2

You can do this just in one line.

e.g to add 5 days

Date newDate = Date.from(Date().toInstant().plus(5, ChronoUnit.DAYS));

to subtract 5 days

Date newDate = Date.from(Date().toInstant().minus(5, ChronoUnit.DAYS));
samtax01
  • 834
  • 9
  • 11
0
Date newDate = new Date();
newDate.setDate(newDate.getDate()+1);
System.out.println(newDate);
  • 14
    fyi, Date.setDate() is deprecated – Kelly S. French Aug 14 '12 at 17:09
  • 1
    On my computer it seems to work across a month border. After `Sun Apr 30 16:25:33 CEST 2017` comes `Mon May 01 16:25:33 CEST 2017`. It’s still a discouraged solution though. Not only is the method deprecated for a good reason, also in 2017 we have very good alternatives to the `Date` class. – Ole V.V. Apr 14 '17 at 14:27
0

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.

  • 1
    I am glad to see you participating in Stack Overflow. But I have to say your Answer has multiple problems. First of all, you are using a type that represents a date with time-of-day as seen in UTC, `java.util.Date`, while the Question asks for only a date, no time-of-day and no time zone or offset-from-UTC. Or perhaps, you meant `java.sql.Date` which is very badly designed as a hack, a subclass of `java.util.Date` that *pretends* to be only a date but actually has a time-of-day, and that asks we ignore the fact it is a subclass of `Date`. – Basil Bourque Apr 03 '21 at 22:57
  • 1
    Both of these wretched classes, `java.util.Date` and `java.sql.Date`, were supplanted years ago by the modern *java.time* classes defined in JSR 310. As for never being deprecated, these classes are entirely replaced by *java.time* functionality, so I expect they will indeed be deprecated some day. Sun, Oracle, and the JCP gave up on these terrible date-time classes with the adoption of JSR 310, and I suggest we all do the same. – Basil Bourque Apr 03 '21 at 22:58
  • 1
    Another problem is that your code only works for UTC. For any other time zone, a day is not necessarily 24 hours long. Days can be 23 or 25 hours, or 23.5 or 25.5 hours long, or any other length dreamed up by politicians. – Basil Bourque Apr 03 '21 at 22:59
  • 1
    The modern solution using *java.time* is also much simpler: `LocalDate.parse( "2021-01-23" ).plusDays( 1 )`. See correct [Answer by Sobral](https://stackoverflow.com/a/20906602/642706). – Basil Bourque Apr 03 '21 at 23:01
  • 1
    Wow thanks I'll study it, I'll check java.time. – Daniele Rugginenti Apr 04 '21 at 18:29