Adding Days to a Date in Java
The SimpleDateFormat class is a concrete implementation of the DateFormat class for formatting and parsing dates in a locale-sensitive manner. It allows the application to format date and time values consistently across different locales.
To add days to a date, we can use the add() method of the Calendar class. The add() method takes a field as the first parameter. The second parameter is the amount of the field to add to the calendar.
Here's an example of how to add 5 days to a date in Java:
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy"); Calendar c = Calendar.getInstance(); c.setTime(new Date()); // Using today's date c.add(Calendar.DATE, 5); // Adding 5 days String output = sdf.format(c.getTime()); System.out.println(output);
In this example, we first create a SimpleDateFormat object. Then, we create a Calendar object and set it to the current date using the setTime() method. Next, we use the add() method to add 5 days to the calendar. Finally, we format the new date using the SimpleDateFormat object and print it out.
以上是如何在 Java 中为日期添加天数?的详细内容。更多信息请关注PHP中文网其他相关文章!