Adding days to a date in Java [duplicate]

匿名 (未验证) 提交于 2019-12-03 02:23:02

问题:

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.

回答1:

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


回答2:

java.time

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

LocalDate.now().plusDays(nrOfDays) 

See the Oracle Tutorial.



回答3:

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



回答4:

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


回答5:

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.



回答6:

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


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!