Home > Java > javaTutorial > How to Add Duration to a Date in Java?

How to Add Duration to a Date in Java?

Linda Hamilton
Release: 2024-11-13 13:54:02
Original
550 people have browsed it

How to Add Duration to a Date in Java?

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:

  1. Parse the date into a Date object using SimpleDateFormat.
  2. Create a Calendar instance and set it to the parsed date.
  3. Use the add() method of the Calendar to add the desired number of days to the date.
  4. Format the new date back into a string using SimpleDateFormat.

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);
Copy after login

This code will output "06/01/2012", which is 5 days after "01/01/2012".

The above is the detailed content of How to Add Duration to a Date in Java?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template