Adding Duration to a Date in Java
One frequent task in programming is manipulating dates. A common requirement is adding a specified duration, such as days, to an existing date. In Java, this can be achieved using the SimpleDateFormat class to parse and format dates, and the Calendar class to add duration.
Adding Days to a Date
To add a number of days to a date, you can use the following steps:
Example
The following code example demonstrates how to add 5 days to the date "01/01/2012" in the "dd/mm/yyyy" format:
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy"); Calendar c = Calendar.getInstance(); c.setTime(sdf.parse("01/01/2012")); c.add(Calendar.DATE, 5); String output = sdf.format(c.getTime()); System.out.println(output);
This code will output "06/01/2012", which is 5 days after "01/01/2012".
以上是如何在 Java 中为日期添加持续时间?的详细内容。更多信息请关注PHP中文网其他相关文章!