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.
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.
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)
plusDays(1)
one could also use minusDays(-1)
. –
Resee getTime()
on your Calendar
instance, and not get(...)
. Also note that months are from 0-11, but days are from 1-31. –
Resee 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 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.
Calendar Timezone
with Daytime Savings, on the changing day from summer to wintertime it will not jump to the next day. –
Marketing 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
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);
LocalDate.of( 2017 , Month.JANUARY , 23 )
.plusDays( 1 )
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 ) ;
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.
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);
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);
Java 8 Time API:
Instant now = Instant.now(); //current date
Instant after= now.plus(Duration.ofDays(300));
Date dateAfter = Date.from(after);
use DateTime object obj.Add to add what ever you want day hour and etc. Hope this works:)
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()
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.
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;
}
}
}
if(year % 4 == 0) { months[1] = 29; }
–
Mirandamire best thing to use:
long currenTime = System.currentTimeMillis();
long oneHourLater = currentTime + TimeUnit.HOURS.toMillis(1l);
Similarly, you can add MONTHS, DAYS, MINUTES etc
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:
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.
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();
}
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
© 2022 - 2024 — McMap. All rights reserved.
java.util.Date
class has been supplanted by thejava.time.Instant
class as of Java 8. – Kilderkin