In this guide, you will learn about the ZonedDateTime plusDays() method in Java programming and how to use it with an example.
1. ZonedDateTime plusDays() Method Overview
Definition:
The plusDays() method of the ZonedDateTime class in Java is used to add the specified number of days to this ZonedDateTime. The calculation is done based on the local date-time, and the time zone is kept unchanged.
Syntax:
ZonedDateTime plusDays(long daysToAdd)
Parameters:
- daysToAdd: The number of days to add; may be negative.
Key Points:
- The plusDays() method returns a new ZonedDateTime instance with the specified number of days added.
- The method handles adjustments in the case of daylight saving time changes and other anomalies, ensuring accurate calculations.
- If the new date-time exceeds the supported range, a DateTimeException will be thrown.
- Adding zero days will have no effect and will return the same instance.
2. ZonedDateTime plusDays() Method Example
import java.time.ZonedDateTime;
import java.time.ZoneId;
public class ZonedDateTimePlusDaysExample {
public static void main(String[] args) {
// Create a ZonedDateTime instance
ZonedDateTime zonedDateTime = ZonedDateTime.of(2023, 9, 20, 12, 34, 56, 0, ZoneId.of("Europe/Paris"));
System.out.println("Original ZonedDateTime: " + zonedDateTime);
// Adding 5 days to the original ZonedDateTime
ZonedDateTime afterAddingDays = zonedDateTime.plusDays(5);
System.out.println("After adding 5 days: " + afterAddingDays);
// Adding a negative number of days (subtracting days)
ZonedDateTime afterSubtractingDays = zonedDateTime.plusDays(-3);
System.out.println("After subtracting 3 days: " + afterSubtractingDays);
}
}
Output:
Original ZonedDateTime: 2023-09-20T12:34:56+02:00[Europe/Paris] After adding 5 days: 2023-09-25T12:34:56+02:00[Europe/Paris] After subtracting 3 days: 2023-09-17T12:34:56+02:00[Europe/Paris]
Explanation:
In the example, we created an original ZonedDateTime instance and used the plusDays() method to add and subtract days. Adding 5 days to the original date resulted in a new date of 2023-09-25, and subtracting 3 days resulted in a new date of 2023-09-17. The time and the time-zone remained unchanged in both cases.
Comments
Post a Comment
Leave Comment