How to add one day to a date? [duplicate]
Asked Answered
R

18

276

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.

Remotion answered 17/6, 2009 at 7:11 Comment(2)
FYI: The troublesome old java.util.Date class has been supplanted by the java.time.Instant class as of Java 8.Kilderkin
Date.from(Instant.now().plusSeconds(86400))Partain
R
613

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);

Solution 4: With org.apache.commons.lang3.time.DateUtils you can do:

Date dt = new Date();
dt = DateUtils.addDays(dt, 1)
Resee answered 17/6, 2009 at 7:18 Comment(8)
For Solution 1 (at least), you can also pass it a negative value (such as -1 to get the day prior).Snood
All solutions support negative offsets, even with their negative counterparts, so instead of plusDays(1) one could also use minusDays(-1).Resee
Solution 3 doesn't end up with a Date.. it ends up with LocalDateTimeWanderjahr
@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 ?South
@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.Resee
FYI, the troublesome old date-time classes such as java.util.Date, java.util.Calendar, and java.text.SimpleDateFormat are now legacy, supplanted by the java.time classes built into Java 8 and later. And the Joda-Time project is now in maintenance mode, with the team advising migration to the java.time classes.Kilderkin
c.setTime(dt); line seems unnecessary, as Calendar c = Calendar.getInstance(); is set to present date and time.Sou
yes it's worked for meValediction
L
98
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.

Lolitaloll answered 17/6, 2009 at 11:6 Comment(8)
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.Marketing
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.Winnie
You are right. I add the hint to this comment to my answer.Lolitaloll
Downvoting since this is very much the wrong answer, due to both daylight saving time and leap seconds. Use Calendar or Joda time.Foreandafter
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.Kilderkin
@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.Hygroscopic
@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.Winnie
@ 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.Hygroscopic
C
36

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
Cyanogen answered 24/8, 2017 at 9:12 Comment(1)
won't handle daylight savings etc. but might be good enough in a pinch :)Combined
H
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);
Hedgehog answered 29/11, 2014 at 2:23 Comment(1)
As mentioned in comments, this will return a LocalDateDime, not a Date.Bluegrass
K
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
Kilderkin answered 11/4, 2014 at 6:8 Comment(3)
scala> java.time.LocalDate.now => res7: java.time.LocalDate = 2018-05-09 scala> java.time.LocalDate.now.plusDays(2) => res9: java.time.LocalDate = 2018-05-11Courtney
@Charlie木匠 ????Kilderkin
Just comment a couple of usage.Courtney
S
22

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

DateUtils.addDays(new Date(), 1);
Sanches answered 28/4, 2016 at 6:5 Comment(1)
A redundant right parenthesis at the end.Andrade
R
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);
Rogers answered 30/12, 2011 at 12:28 Comment(0)
H
5

Java 8 Time API:

Instant now = Instant.now(); //current date
Instant after= now.plus(Duration.ofDays(300));
Date dateAfter = Date.from(after);
Hiltner answered 26/11, 2016 at 10:6 Comment(2)
I think this is Java 8 APIFugato
Thanks, of course, fixHiltner
B
4

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

Biforked answered 17/6, 2009 at 11:54 Comment(0)
S
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()
Syman answered 29/11, 2012 at 17:0 Comment(1)
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.Marquetry
P
4

Java 8 LocalDate API

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

Preclude answered 30/3, 2017 at 1:46 Comment(0)
S
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.

Swink answered 17/6, 2009 at 8:56 Comment(0)
M
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;
        }
    }
}
Mountfort answered 30/11, 2014 at 5:45 Comment(3)
For a performance point of view, the solution is very interresting. +1Marquetry
This doesn't work with leap years.Gilman
By putting simple condition you can handle leap year as well. if(year % 4 == 0) { months[1] = 29; }Mirandamire
D
3

best thing to use:

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

Similarly, you can add MONTHS, DAYS, MINUTES etc

Darcee answered 13/8, 2015 at 19:27 Comment(0)
A
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:

Artemisia answered 4/5, 2015 at 6:59 Comment(0)
A
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.

Armentrout answered 28/4, 2016 at 6:45 Comment(0)
R
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();
    }
Regrate answered 8/6, 2016 at 6:31 Comment(0)
H
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
Haemostatic answered 15/8, 2016 at 16:56 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.