Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add one day to a date? [duplicate]

Tags:

java

datetime

People also ask

How do you add one day to a new date?

const date = new Date(); date. setDate(date. getDate() + 1); // ✅ 1 Day added console.

How do I add days to a date in Java?

Use the add() method of the calendar class to add days to the date. The add method() takes two parameter, i.e., calendar field and amount of time that needs to be added. Get the new date from the calendar and set the format of the SimpleDateFormat class to show the calculated new date on the screen.

How can I get tomorrow date in dd mm yyyy format in Java?

get(Calendar. DAY_OF_MONTH) + 1; will it display tomorrow's date. or just add one to today's date? For example, if today is January 31.


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

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.


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

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

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?

  • Java SE 8, Java SE 9, Java SE 10, and later
    • Built-in.
    • Part of the standard Java API with a bundled implementation.
    • Java 9 adds some minor features and fixes.
  • Java SE 6 and Java SE 7
    • Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
  • Android
    • Later versions of Android bundle implementations of the java.time classes.
    • For earlier Android (<26), the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….

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

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

DateUtils.addDays(new Date(), 1);