271

I want to add one day to a particular date. How can I do that?

Date dt = new Date();

Now I want to add one day to this date.

Daniel Rikowski
  • 71,375
  • 57
  • 251
  • 329
user93796
  • 18,749
  • 31
  • 94
  • 150

18 Answers18

607

Given a Date dt you have several possibilities:

Solution 1: You can use the Calendar class for that:

Date dt = new Date();
Calendar c = Calendar.getInstance(); 
c.setTime(dt); 
c.add(Calendar.DATE, 1);
dt = c.getTime();

Solution 2: You should seriously consider using the Joda-Time library, because of the various shortcomings of the Date class. With Joda-Time you can do the following:

Date dt = new Date();
DateTime dtOrg = new DateTime(dt);
DateTime dtPlusOne = dtOrg.plusDays(1);

Solution 3: With Java 8 you can also use the new JSR 310 API (which is inspired by Joda-Time):

Date dt = new Date();
LocalDateTime.from(dt.toInstant()).plusDays(1);
Nissa
  • 4,636
  • 8
  • 29
  • 37
Daniel Rikowski
  • 71,375
  • 57
  • 251
  • 329
  • 4
    For Solution 1 (at least), you can also pass it a negative value (such as -1 to get the day prior). – welshk91 May 30 '17 at 21:20
  • 3
    All solutions support negative offsets, even with their negative counterparts, so instead of `plusDays(1)` one could also use `minusDays(-1)`. – Daniel Rikowski May 31 '17 at 09:00
  • 50
    Solution 3 doesn't end up with a Date.. it ends up with LocalDateTime – Charbel Jul 06 '17 at 20:55
  • @DanielRikowski If i am adding 1 day to the last day of month in calendar object, the month remains same instead of moving to next month, how to make that work ? – Derrick Jan 30 '18 at 06:48
  • 1
    @DerickDaniel There must be something wrong with your surrounding code. All three solutions correctly wrap at month/year boundaries. Make sure you are calling `getTime()` on your `Calendar` instance, and not `get(...)`. Also note that months are from 0-11, but days are from 1-31. – Daniel Rikowski Jan 30 '18 at 10:37
  • 1
    FYI, the 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`, 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. And the [*Joda-Time*](http://www.joda.org/joda-time/) project is now in maintenance mode, with the team advising migration to the *java.time* classes. – Basil Bourque May 09 '18 at 23:29
  • c.setTime(dt); line seems unnecessary, as Calendar c = Calendar.getInstance(); is set to present date and time. – Yar Dec 05 '18 at 15:42
  • yes it's worked for me – Bipin Bharti Oct 12 '20 at 16:28
97
Date today = new Date();
Date tomorrow = new Date(today.getTime() + (1000 * 60 * 60 * 24));

Date has a constructor using the milliseconds since the UNIX-epoch. the getTime()-method gives you that value. So adding the milliseconds for a day, does the trick. If you want to do such manipulations regularly I recommend to define constants for the values.

Important hint: That is not correct in all cases. Read the WARNING comment, below.

rogerdpack
  • 62,887
  • 36
  • 269
  • 388
Mnementh
  • 50,487
  • 48
  • 148
  • 202
  • 61
    WARNING! Adding 1000*60*60*24 milliseconds to a java date will once in a great while add zero days or two days to the original date in the circumstances of leap seconds, daylight savings time and the like. If you need to be 100% certain only one day is added, this solution is not the one to use. – Eric Leschinski Mar 13 '13 at 22:39
  • 2
    You are right. I add the hint to this comment to my answer. – Mnementh Mar 14 '13 at 10:51
  • 2
    Downvoting since this is very much the wrong answer, due to both daylight saving time and leap seconds. Use Calendar or Joda time. – stolsvik Feb 02 '14 at 22:26
  • 1
    Leap seconds are not an issue in this context, as they are ignored by these date-time libraries: java.util.Date, Joda-Time, and java.time. The real problem with this answer is anomalies such as Daylight Savings Time that result in a day being other than exactly 24 hours long. – Basil Bourque May 01 '14 at 15:06
  • @Eric Leschinski You are assuming that the Date class knows about leap seconds, which it certainly does not appear to despite the woffly comment at the top. Most systems just adjust the computer clock as happens anyway. But in any case I cannot see it failing by more than one second. – Tuntable Dec 29 '15 at 00:09
  • @aberglas, You're not thinking through the problem. You're thinking in terms of wrongness relative to itself, I'm talking about wrongness relative to the system time. Date is flawless keeper of time with no notion of leap seconds. But the system time is, so sometimes adding 1000*60*60*24 milliseconds to a Date keeps you on the same day, or takes you forward to the 2nd day relative to the system time. Date does the perfect thing, and your system clock does the weird thing. The system time gets the final say on what time it is, so therefore Date's perfect calculation is wrong. – Eric Leschinski Dec 29 '15 at 00:51
  • @ Eric Leschinski I'm pretty sure that System.currentTimeMilliseconds is the number of milliseconds since 1970 MINUS the number of leap seconds added since 1970. In other words there can be two times with the same currentTimeMilliseconds. It has to be like that, or it would break almost all software. – Tuntable Jan 05 '16 at 03:22
  • I would be careful using Date today = new Date(); Date tomorrow = new Date(today.getTime() + (1000 * 60 * 60 * 24)); If you are using a `Calendar Timezone` with Daytime Savings, on the changing day from summer to wintertime it will not jump to the next day. – katana0815 Nov 29 '12 at 16:52
35

I found a simple method to add arbitrary time to a Date object

Date d = new Date(new Date().getTime() + 86400000)

Where:

86 400 000 ms = 1 Day  : 24*60*60*1000
 3 600 000 ms = 1 Hour :    60*60*1000
Olivier Grégoire
  • 33,839
  • 23
  • 96
  • 137
plailopo
  • 683
  • 1
  • 7
  • 12
28

As mentioned in the Top answer, since java 8 it is possible to do:

Date dt = new Date();
LocalDateTime.from(dt.toInstant()).plusDays(1);

but this can sometimes lead to an DateTimeException like this:

java.time.DateTimeException: Unable to obtain LocalDateTime from TemporalAccessor: 2014-11-29T03:20:10.800Z of type java.time.Instant

It is possible to avoid this Exception by simply passing the time zone:

LocalDateTime.from(dt.toInstant().atZone(ZoneId.of("UTC"))).plusDays(1);
hnefatl
  • 5,860
  • 2
  • 27
  • 49
behzad
  • 965
  • 11
  • 24
23

tl;dr

LocalDate.of( 2017 , Month.JANUARY , 23 ) 
         .plusDays( 1 )

java.time

Best to avoid the java.util.Date class altogether. But if you must do so, you can convert between the troublesome old legacy date-time classes and the modern java.time classes. Look to new methods added to the old classes.

Instant

The Instant class, is close to being equivalent to Date, both being a moment on the timeline. Instant resolves to nanoseconds, while Date is milliseconds.

Instant instant = myUtilDate.toInstant() ;

You could add a day to this, but keep in mind this in UTC. So you will not be accounting for anomalies such as Daylight Saving Time. Specify the unit of time with the ChronoUnit class.

Instant nextDay = instant.plus( 1 , ChronoUnit.DAYS ) ;

ZonedDateTime

If you want to be savvy with time zones, specify a ZoneId to get a ZonedDateTime. Specify a proper time zone name in the format of continent/region, such as America/Montreal, Africa/Casablanca, or Pacific/Auckland. Never use the 3-4 letter abbreviation such as EST or IST as they are not true time zones, not standardized, and not even unique(!).

ZoneId z = ZoneId.of( "America/Montreal" ) ;
ZonedDateTime zdt = instant.atZone( z ) ;
ZonedDateTime zdtNextDay = zdt.plusDays( 1 ) ;

You can also represent your span-of-time to be added, the one day, as a Period.

Period p = Period.ofDays( 1 ) ;
ZonedDateTime zdt = ZonedDateTime.now( z ).plus( p ) ;

You may want the first moment of that next day. Do not assume the day starts at 00:00:00. Anomalies such as Daylight Saving Time (DST) mean the day may start at another time, such as 01:00:00. Let java.time determine the first moment of the day on that date in that zone.

LocalDate today = LocalDate.now( z ) ;
LocalDate tomorrow = today.plus( p ) ;
ZonedDateTime zdt = tomorrow.atStartOfDay( z ) ;

About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.

Where to obtain the java.time classes?

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.


Update: The Joda-Time library is now in maintenance mode. The team advises migration to the java.time classes. I am leaving this section intact for history.

Joda-Time

The Joda-Time 2.3 library makes this kind of date-time work much easier. The java.util.Date class bundled with Java is notoriously troublesome, and should be avoided.

Here is some example code.

Your java.util.Date is converted to a Joda-Time DateTime object. Unlike a j.u.Date, a DateTime truly knows its assigned time zone. Time zone is crucial as adding a day to get the same wall-clock time tomorrow might mean making adjustments such as for a 23-hour or 25-hour day in the case of Daylight Saving Time (DST) here in the United States. If you specify the time zone, Joda-Time can make that kind of adjustment. After adding a day, we convert the DateTime object back into a java.util.Date object.

java.util.Date yourDate = new java.util.Date();

// Generally better to specify your time zone rather than rely on default.
org.joda.time.DateTimeZone timeZone = org.joda.time.DateTimeZone.forID( "America/Los_Angeles" );
DateTime now = new DateTime( yourDate, timeZone );
DateTime tomorrow = now.plusDays( 1 );
java.util.Date tomorrowAsJUDate = tomorrow.toDate();

Dump to console…

System.out.println( "yourDate: " + yourDate );
System.out.println( "now: " + now );
System.out.println( "tomorrow: " + tomorrow );
System.out.println( "tomorrowAsJUDate: " + tomorrowAsJUDate );

When run…

yourDate: Thu Apr 10 22:57:21 PDT 2014
now: 2014-04-10T22:57:21.535-07:00
tomorrow: 2014-04-11T22:57:21.535-07:00
tomorrowAsJUDate: Fri Apr 11 22:57:21 PDT 2014
Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
22

you can use this method after import org.apache.commons.lang.time.DateUtils:

DateUtils.addDays(new Date(), 1);
rajeev pani..
  • 5,387
  • 5
  • 27
  • 35
xiangmao_lxm
  • 221
  • 2
  • 5
13

This will increase any date by exactly one

String untildate="2011-10-08";//can take any date in current format    
SimpleDateFormat dateFormat = new SimpleDateFormat( "yyyy-MM-dd" );   
Calendar cal = Calendar.getInstance();    
cal.setTime( dateFormat.parse(untildate));    
cal.add( Calendar.DATE, 1 );    
String convertedDate=dateFormat.format(cal.getTime());    
System.out.println("Date increase by one.."+convertedDate);
Stephen
  • 1,737
  • 2
  • 26
  • 37
navneet
  • 147
  • 1
  • 2
5

Java 8 Time API:

Instant now = Instant.now(); //current date
Instant after= now.plus(Duration.ofDays(300));
Date dateAfter = Date.from(after);
Grigory Kislin
  • 16,647
  • 10
  • 125
  • 197
4

use DateTime object obj.Add to add what ever you want day hour and etc. Hope this works:)

Vinay Pandey
  • 8,589
  • 9
  • 36
  • 54
4

I prefer joda for date and time arithmetics because it is much better readable:

Date tomorrow = now().plusDays(1).toDate();

Or

endOfDay(now().plus(days(1))).toDate()
startOfDay(now().plus(days(1))).toDate()
remipod
  • 11,269
  • 1
  • 22
  • 25
  • and the performance is not important ? If you must do these computations on many instances, it's very expensive. Readable is one thing but it should be think in a broader way. – davidxxx Feb 16 '16 at 10:43
4

Java 8 LocalDate API

LocalDate.now().plusDays(1L);

Filip Bartuzi
  • 5,711
  • 7
  • 54
  • 102
traeper
  • 452
  • 6
  • 9
3

To make it a touch less java specific, the basic principle would be to convert to some linear date format, julian days, modified julian days, seconds since some epoch, etc, add your day, and convert back.

The reason for doing this is that you farm out the "get the leap day, leap second, etc right' problem to someone who has, with some luck, not mucked this problem up.

I will caution you that getting these conversion routines right can be difficult. There are an amazing number of different ways that people mess up time, the most recent high profile example was MS's Zune. Dont' poke too much fun at MS though, it's easy to mess up. It doesn't help that there are multiple different time formats, say, TAI vs TT.

Bruce ONeel
  • 2,069
  • 1
  • 11
  • 3
3

In very special case If you asked to do your own date class, possibly from your Computer Programming Professor; This method would do very fine job.

public void addOneDay(){
    int [] months = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
    day++;
    if (day> months[month-1]){
        month++;
        day = 1;
        if (month > 12){
            year++;
            month = 1;
        }
    }
}
Durgpal Singh
  • 11,481
  • 4
  • 37
  • 49
Burak
  • 57
  • 7
3

best thing to use:

      long currenTime = System.currentTimeMillis();
      long oneHourLater = currentTime + TimeUnit.HOURS.toMillis(1l);

Similarly, you can add MONTHS, DAYS, MINUTES etc

gaurav414u
  • 812
  • 13
  • 22
2

Java 1.8 version has nice update for data time API.

Here is snippet of code:

    LocalDate lastAprilDay = LocalDate.of(2014, Month.APRIL, 30);
    System.out.println("last april day: " + lastAprilDay);
    LocalDate firstMay = lastAprilDay.plusDays(1);
    System.out.println("should be first may day: " + firstMay);
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd");
    String formatDate = formatter.format(firstMay);
    System.out.println("formatted date: " + formatDate);

Output:

last april day: 2014-04-30
should be first may day: 2014-05-01
formatted date: 01

For more info see Java documentations to this classes:

catch23
  • 17,519
  • 42
  • 144
  • 217
2

U can try java.util.Date library like this way-

int no_of_day_to_add = 1;

Date today = new Date();
Date tomorrow = new Date( today.getYear(), today.getMonth(), today.getDate() + no_of_day_to_add );

Change value of no_of_day_to_add as you want.

I have set value of no_of_day_to_add to 1 because u wanted only one day to add.

More can be found in this documentation.

Abrar Jahin
  • 13,970
  • 24
  • 112
  • 161
2

you want after days find date this code try..

public Date getToDateAfterDays(Integer day) {
        Date nowdate = new Date();
        Calendar cal = Calendar.getInstance();
        cal.setTime(nowdate);
        cal.add(Calendar.DATE, day);
        return cal.getTime();
    }
2

I will show you how we can do it in Java 8. Here you go:

public class DemoDate {
    public static void main(String[] args) {
        LocalDate today = LocalDate.now();
        System.out.println("Current date: " + today);

        //add 1 day to the current date
        LocalDate date1Day = today.plus(1, ChronoUnit.DAYS);
        System.out.println("Date After 1 day : " + date1Day);
    }
}

The output:

Current date: 2016-08-15
Date After 1 day : 2016-08-16
PAA
  • 1
  • 46
  • 174
  • 282