Java ZonedDateTime minusWeeks()

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

1. ZonedDateTime minusWeeks() Method Overview

Definition:

The minusWeeks() method of the ZonedDateTime class in Java is used to subtract the specified number of weeks from this ZonedDateTime. The calculation is done based on the local date-time, and the time zone is kept unchanged.

Syntax:

ZonedDateTime minusWeeks(long weeksToSubtract)

Parameters:

- weeksToSubtract: The number of weeks to subtract; may be negative.

Key Points:

- The minusWeeks() method returns a new ZonedDateTime instance with the specified number of weeks subtracted.

- 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.

- Subtracting zero weeks will have no effect and will return the same instance.

2. ZonedDateTime minusWeeks() Method Example

import java.time.ZonedDateTime;
import java.time.ZoneId;

public class ZonedDateTimeMinusWeeksExample {
    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);

        // Subtracting 2 weeks from the original ZonedDateTime
        ZonedDateTime afterSubtractingWeeks = zonedDateTime.minusWeeks(2);
        System.out.println("After subtracting 2 weeks: " + afterSubtractingWeeks);

        // Subtracting a negative number of weeks (adding weeks)
        ZonedDateTime afterAddingWeeks = zonedDateTime.minusWeeks(-3);
        System.out.println("After adding 3 weeks: " + afterAddingWeeks);
    }
}

Output:

Original ZonedDateTime: 2023-09-20T12:34:56+02:00[Europe/Paris]
After subtracting 2 weeks: 2023-09-06T12:34:56+02:00[Europe/Paris]
After adding 3 weeks: 2023-10-11T12:34:56+02:00[Europe/Paris]

Explanation:

In the example, we created an original ZonedDateTime instance and used the minusWeeks() method to subtract and add weeks. Subtracting 2 weeks from the original date resulted in a new date of 2023-09-06, and adding 3 weeks resulted in a new date of 2023-10-11. The time and the time zone remained unchanged in both cases.

Comments