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

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


Something like this should do the trick:

String dt = "2008-01-01";  // Start dateSimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");Calendar c = Calendar.getInstance();c.setTime(sdf.parse(dt));c.add(Calendar.DATE, 1);  // number of days to adddt = sdf.format(c.getTime());  // dt is now the new date


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


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