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

Viewed 1099382

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

How can I increment this date by one day?

31 Answers

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

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);
SimpleDateFormat dateFormat = new SimpleDateFormat( "yyyy-MM-dd" );
Calendar cal = Calendar.getInstance();
cal.setTime( dateFormat.parse( inputString ) );
cal.add( Calendar.DATE, 1 );

Construct a Calendar object and call 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));

In Java 8 simple way to do is:

Date.from(Instant.now().plusSeconds(SECONDS_PER_DAY))
startCalendar.add(Calendar.DATE, 1); //Add 1 Day to the current Calender

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

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.

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'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

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

Some approaches:

  1. Convert to string and back with SimpleDateFormat: This is an inefficient solution.
  2. Convert to LocalDate: You would lose any time-of-day information.
  3. Convert to LocalDateTime: This involves more steps and you need to worry about timezone.
  4. 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);

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

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.

Related