I'm working with a date in this format: yyyy-mm-dd
.
How can I increment this date by one day?
Join Stack Overflow to learn, share knowledge, and build your career.
I'm working with a date in this format: yyyy-mm-dd
.
How can I increment this date by one day?
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
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);
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. See Tutorial by Oracle.
– Basil Bourque
Jul 31 '18 at 7:30
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();
}
}
ZonedDateDateTime
and OffsetDateTime
also have plusDays
and minusDays
methods as well as LocalDate
– Basil Bourque
Mar 16 '16 at 16:48
LocalDate
.
– Daniel C. Sobral
Mar 16 '16 at 19:12
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.
SimpleDateFormat dateFormat = new SimpleDateFormat( "yyyy-MM-dd" );
Calendar cal = Calendar.getInstance();
cal.setTime( dateFormat.parse( inputString ) );
cal.add( Calendar.DATE, 1 );
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));
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!
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);
you can use Simple java.util lib
Calendar cal = Calendar.getInstance();
cal.setTime(yourDate);
cal.add(Calendar.DATE, 1);
yourDate = cal.getTime();
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. See Tutorial by Oracle.
– Basil Bourque
Nov 27 '18 at 20:29
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.
Date
or Calendar
again.
– Basil Bourque
Jul 29 '18 at 20:22
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
LocalDate
class not LocalDateTime
.
– Basil Bourque
May 27 '17 at 6:31
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.
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));
LocalDate
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 project.
– Basil Bourque
Feb 24 '17 at 22:10
In Java 8 simple way to do is:
Date.from(Instant.now().plusSeconds(SECONDS_PER_DAY))
Instant.now().plus( 1 , ChronoUnit.DAYS )
?
– Basil Bourque
Jul 31 '18 at 7:28
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
startCalendar.add(Calendar.DATE, 1); //Add 1 Day to the current Calender
Calendar
class in 2019.
– Ole V.V.
Feb 18 '19 at 9:19
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"));
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);
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.
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;
}
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
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.
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
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 9 '19 at 15:31
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);
Date
class in 2018 is poor advice. 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 & Java 9. See Tutorial by Oracle. See other Answers using LocalDate
class.
– Basil Bourque
Feb 27 '18 at 19:55
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
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);
}
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
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();
}
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 at 14:38
Let's clarify the use case: You want to do calendar arithmetic and start/end with a java.util.Date.
Some approaches:
Consider using java.time.Instant:
Date _now = new Date();
Instant _instant = _now.toInstant().minus(5, ChronoUnit.DAYS);
Date _newDate = Date.from(_instant);
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
Date newDate = new Date();
newDate.setDate(newDate.getDate()+1);
System.out.println(newDate);
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
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.
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 3 at 22:57
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 3 at 22:58
LocalDate.parse( "2021-01-23" ).plusDays( 1 )
. See correct Answer by Sobral.
– Basil Bourque
Apr 3 at 23:01