Adding days to a date in Java [duplicate]

2019-01-01 05:53发布

This question already has an answer here:

How do I add x days to a date in Java?

For example, my date is (dd/mm/yyyy) = 01/01/2012

Adding 5 days, the output should be 06/01/2012.

标签: java date
6条回答
看风景的人
2楼-- · 2019-01-01 06:08
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
Calendar c = Calendar.getInstance();
c.setTime(new Date()); // Now use today date.
c.add(Calendar.DATE, 5); // Adding 5 days
String output = sdf.format(c.getTime());
System.out.println(output);
查看更多
笑指拈花
3楼-- · 2019-01-01 06:08

If you're using Joda-Time (and there are lots of good reasons to - a simple, intuitive API and thread-safety) then you can do this trivially:

(new LocalDate()).plusDays(5);

to give 5 days from today, for example.

查看更多
回忆,回不去的记忆
4楼-- · 2019-01-01 06:11

Simple, without any other API:

To add 8 days:

Date today=new Date();
long ltime=today.getTime()+8*24*60*60*1000;
Date today8=new Date(ltime);
查看更多
墨雨无痕
5楼-- · 2019-01-01 06:15
Calendar cal = Calendar.getInstance();    
cal.set(Calendar.DAY_OF_MONTH, 1);
cal.set(Calendar.MONTH, 1);
cal.set(Calendar.YEAR, 2012);
cal.add(Calendar.DAY_OF_MONTH, 5);

You can also substract days like Calendar.add(Calendar.DAY_OF_MONTH, -5);

查看更多
孤独总比滥情好
6楼-- · 2019-01-01 06:18

Here is some simple code to give output as currentdate + D days = some 'x' date (future date):

DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");

Calendar c = Calendar.getInstance();    
c.add(Calendar.DATE, 5);
System.out.println(dateFormat.format(c.getTime()));
查看更多
浪荡孟婆
7楼-- · 2019-01-01 06:31

java.time

With the Java 8 Date and Time API you can use the LocalDate class.

LocalDate.now().plusDays(nrOfDays)

See the Oracle Tutorial.

查看更多
登录 后发表回答