Java LocalDateTime plusDays()

🎓 Check Out My Top 25 Udemy Courses (80-90% Discount): My Udemy Courses - Ramesh Fadatare

In this guide, you will learn about the LocalDateTime plusDays() method in Java programming and how to use it with an example.

1. LocalDateTime plusDays() Method Overview

Definition:

The LocalDateTime.plusDays() method returns a copy of the LocalDateTime with the specified number of days added.

Syntax:

LocalDateTime plusDays(long days)

Parameters:

- days: The number of days to add, may be negative.

Key Points:

- The LocalDateTime.plusDays() method is useful for date arithmetic where you want to manipulate the day part of a LocalDateTime.

- The returned LocalDateTime instance is immutable, which means the original LocalDateTime instance remains unchanged.

- The method takes care of month and year boundaries. For example, adding 1 day to the last day of a month will return the first day of the next month.

- If adding the days results in an overflow of the maximum date (LocalDateTime.MAX), a DateTimeException will be thrown.

2. LocalDateTime plusDays() Method Example

import java.time.LocalDateTime;

public class LocalDateTimePlusDaysExample {
    public static void main(String[] args) {
        LocalDateTime dateTime = LocalDateTime.of(2023, 12, 31, 16, 30);

        // Add 1 day to the LocalDateTime
        LocalDateTime result1 = dateTime.plusDays(1);

        // Subtract 5 days from the LocalDateTime
        LocalDateTime result2 = dateTime.plusDays(-5);

        System.out.println("Original DateTime: " + dateTime);
        System.out.println("After adding 1 day: " + result1);
        System.out.println("After subtracting 5 days: " + result2);
    }
}

Output:

Original DateTime: 2023-12-31T16:30
After adding 1 day: 2024-01-01T16:30
After subtracting 5 days: 2023-12-26T16:30

Explanation:

In the example, we have a LocalDateTime set to December 31, 2023.

- When we add 1 day using plusDays(1), the date becomes January 1, 2024, which demonstrates the method's capability to handle month and year boundaries.

- When we subtract 5 days using plusDays(-5), the date becomes December 26, 2023.

My Top and Bestseller Udemy Courses. The sale is going on with a 70 - 80% discount. The discount coupon has been added to each course below:

Comments

Spring Boot 3 Paid Course Published for Free
on my Java Guides YouTube Channel

Subscribe to my YouTube Channel (165K+ subscribers):
Java Guides Channel

Top 10 My Udemy Courses with Huge Discount:
Udemy Courses - Ramesh Fadatare