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

2018-12-31 01:23发布

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

How can I increment this date by one day?

标签: java date
25条回答
裙下三千臣
2楼-- · 2018-12-31 02:01
SimpleDateFormat dateFormat = new SimpleDateFormat( "yyyy-MM-dd" );
Calendar cal = Calendar.getInstance();
cal.setTime( dateFormat.parse( inputString ) );
cal.add( Calendar.DATE, 1 );
查看更多
呛了眼睛熬了心
3楼-- · 2018-12-31 02:04

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.

查看更多
牵手、夕阳
4楼-- · 2018-12-31 02:06

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);
查看更多
低头抚发
5楼-- · 2018-12-31 02:06

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!

查看更多
临风纵饮
6楼-- · 2018-12-31 02:07

Construct a Calendar object and use the method add(Calendar.DATE, 1);

查看更多
ら面具成の殇う
7楼-- · 2018-12-31 02:08
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.

查看更多
登录 后发表回答