ChatGPT解决这个技术问题 Extra ChatGPT

How can I increment a date by one day in Java?

I'm working with a date in this format: yyyy-mm-dd.

How can I increment this date by one day?

If you are using Java 8 or newer you can use the new date/time api. See this answer: stackoverflow.com/a/23910924/1115554
new DateTime().plusDays(1).toDate() ???

S
Sam Hasler

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

@Esko, c.roll(Calendar.DATE, true) won't roll the month on the last day of the month.
I'll quote some JavaDocs... Calendar.DATE: "...This is a synonym for DAY_OF_MONTH." I wish the JavaDocs would clarify that this would increment larger fields (like the month and year). Calendar.roll "Adds or subtracts (up/down) a single unit of time on the given time field without changing larger fields" .. Again, "larger fields" is vague but that seems consistent with Sam's comment. I wish there were a StackOverflow for fixing old the JavaDocs.
guys, unfortunately, it's quite useless to add days using DATE, DAY_OF_MONTH or even DAY_OF_YEAR - they all are incremented by modulus. So considering Calendar of 31-12-1970, add(DAY_OF_YEAR, 1) or roll(), however roll() finally calls add(), will give 01-01-1970. I guess the only correct way is to set time with milliseconds. As for me, I'm never using Calendar class again.
@Bagzerg: You are wrong. add() will roll the date. See on ideone.
FYI, the terribly 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. See Tutorial by Oracle.
L
Lisa

UPDATE (May 2021): This is a really outdated answer for old, old Java. For Java 8 and above, see https://stackoverflow.com/a/20906602/314283

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

FYI, the terribly 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. See Tutorial by Oracle.
B
Basil Bourque

java.time

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

FYI, both ZonedDateDateTime and OffsetDateTime also have plusDays and minusDays methods as well as LocalDate
@BasilBourque Sure, but the information available in the question is that of a LocalDate.
@DanielCSobral Yep. Just adding links for your readers’ edification. Not a criticism.
E
Edward Anderson

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.


A
Alex B
SimpleDateFormat dateFormat = new SimpleDateFormat( "yyyy-MM-dd" );
Calendar cal = Calendar.getInstance();
cal.setTime( dateFormat.parse( inputString ) );
cal.add( Calendar.DATE, 1 );

N
Neuron

Construct a Calendar object and call add(Calendar.DATE, 1);


m
micha

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

I guess you meant januaryFirst.plusDays(1) not date.plusDays(1).
@Subho For Android before 26, see the ThreeTenABP project that adapts the ThreeTen-Backport project, a back-port if most of the java-time functionality to Java 6 and Java 7.
J
JodaStephen

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

You can remove the parser calls for constructing the DateTime. Use DateTime date = new DateTime(dateString); Then, nextDay is ISODateTimeFormat.date().print(date.plusDays(1)); See joda-time.sourceforge.net/api-release/org/joda/time/… for more info.
For more detailed example code using Joda-Time, see my answer to a similar question, How to add one day to a date?.
FYI… The Joda-Time project is now in maintenance-mode, and advises migration to the java.time classes. Both efforts were led by the same man, Stephen Colebourne. So they share similar concepts, and migration is not difficult.
F
Florian R.

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!


P
Pawan Pareek

you can use Simple java.util lib

Calendar cal = Calendar.getInstance(); 
cal.setTime(yourDate); 
cal.add(Calendar.DATE, 1);
yourDate = cal.getTime();

This Answer duplicates the content of multiple Answers including the accepted Answer from three years ago. Please delete your Answer or edit to add value.
this answer is cleaner, doesnt parse the date in the middle. the "accepted answer" is too convoluted. it's good you added yours, disregard basil's automated remark
FYI, the terribly 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. See Tutorial by Oracle.
Best answer, straight to the point. I agree with Mickey, just disregard basil's comment
R
Rey
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.


you can do something like c.setTime(Date object) to set a specific Date before adding.
I wish the default java packages would make handling dates less convoluted... I mean it's such a pain every time you want to deal with dates... just a rant...
@Shn_Android_Dev The java.time classes built into Java 8 and later supplant the terrible old date-time classes, and answer your wish. Also back-ported to Java 6/7 & earlier Android in the ThreeTen-Backport and ThreeTenABP projects. No need to ever use Date or Calendar again.
A
Avijit Karmakar

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

No, the Question asked for a date-only value not a date-time. So use the LocalDate class not LocalDateTime.
Your Answer repeats the content of at least four other Answers. Please explain how yours adds value beyond those, or else delete before you collect down-votes.
J
Jens

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

This creates a date-time value where the Question asks for a date-only. I suggest a much wiser approach is the 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.
d
dvaey
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.


This is probably not what OP wanted; it doesn't make any allowance for Daylight Savings-type adjustments, leap seconds and so on.
Daylight savings should be handled by timezone/locale. My example was showing how to increment by small durations. When incrementing by days, leap seconds can be an issue but when adding hours, it is less likely although still possible.
d
dpk

In Java 8 simple way to do is:

Date.from(Instant.now().plusSeconds(SECONDS_PER_DAY))

Seems a bit of a stretch. Why not just go with Instant.now().plus( 1 , ChronoUnit.DAYS ) ?
Y
Yoon5oo

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


it's better to use synonym constant Calendar.DAY_OF_MONTH for code readability
A
Abdurahman Popal
startCalendar.add(Calendar.DATE, 1); //Add 1 Day to the current Calender

Thank you for wanting to contribute. However this is already in several of the other answers, so I really see no point… Apart from that IMHO nobody should use the poorly designed and long outdated Calendar class in 2019.
it's better to use synonym constant Calendar.DAY_OF_MONTH for code readability
R
Ramesh-X

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

e
eHayik

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

R
ROCKY

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.


L
LMK

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;

}

t
terrmith

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

There is no accepted answer and I felt there was overall confusion if other fields are updated aswell.
R
Ross

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.


R
Rachid Azzanati

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

It looks correct, but the 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.
Hello, I totally agree with you, but I have not seen the second highest voted answer before publishing mine.
it's better to use synonym constant Calendar.DAY_OF_MONTH for code readability
M
Mike T

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


This code uses the terrible 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 )
J
JonathanDavidArndt

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

Suggesting 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.
Yes it is, LocalDate IS the best way to do that,
however some frameworks like jsf have a little integration problems with time API so sometimes you should use Date; plus environment java < 8
@Lucke Most of the java.time functionality was back-ported to Java 6 & 7 in the ThreeTen-Backport project. Further adapted to older Android in ThreeTenABP project. So, really no need to ever touch those bloody awful old date-time classes. Many frameworks have been updated. But not all. So if you must interoperate with old code not yet updated to java.time, write your new code in java.time and convert to/from the old types by calling new conversion methods added to the old classes.
This code ignores the crucial issue of time zone. For any given moment, the date varies around the glob by zone. The 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.
E
Evan

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

Even simpler: Drop the formatter and just use toString() to produce the string i yyyy-MM-dd format (and if you insist, remember that mm is minutes while MM is the month).
C
Chad Juliano

Let's clarify the use case: You want to do calendar arithmetic and start/end with a java.util.Date.

Some approaches:

Convert to string and back with SimpleDateFormat: This is an inefficient solution. Convert to LocalDate: You would lose any time-of-day information. Convert to LocalDateTime: This involves more steps and you need to worry about timezone. Convert to epoch with Date.getTime(): This is efficient but you are calculating with milliseconds.

Consider using java.time.Instant:

Date _now = new Date();
Instant _instant = _now.toInstant().minus(5, ChronoUnit.DAYS);
Date _newDate = Date.from(_instant);

Never mix the terrible legacy classes such as 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.
Does not address the Question. You are using classes representing a moment (a date with time-of-day in context of an offset or zone). But the Question asks about date-only without time-of-day and without time zone. See correct Answer by Sobral and correct Answer by micha.
s
samtax01

You can do this just in one line.

e.g to add 5 days

Date newDate = Date.from(Date().toInstant().plus(5, ChronoUnit.DAYS));

to subtract 5 days

Date newDate = Date.from(Date().toInstant().minus(5, ChronoUnit.DAYS));

F
Filip Trajcevski
Date newDate = new Date();
newDate.setDate(newDate.getDate()+1);
System.out.println(newDate);

fyi, Date.setDate() is deprecated
On my computer it seems to work across a month border. After 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.