OffsetDateTime minusYears() method in Java with examples
The minusYears()
method is a part of the OffsetDateTime
class in Java. It is used to subtract a specified number of years from the current OffsetDateTime
object and return a new OffsetDateTime
object with the updated value.
Syntax:
public OffsetDateTime minusYears(long years)
Parameters:
- years
: The number of years to subtract from the current OffsetDateTime
object.
Returns:
- A new OffsetDateTime
object with the updated value after subtracting the specified number of years.
Example 1:
OffsetDateTime currentDateTime = OffsetDateTime.now();
System.out.println("Current OffsetDateTime: " + currentDateTime);
OffsetDateTime updatedDateTime = currentDateTime.minusYears(2);
System.out.println("Updated OffsetDateTime: " + updatedDateTime);
Output:
Current OffsetDateTime: 2021-10-14T16:30:45.123456789+05:30
Updated OffsetDateTime: 2019-10-14T16:30:45.123456789+05:30
In the above example, we first create an OffsetDateTime
object representing the current date and time using the now()
method. We then subtract 2 years from this object using the minusYears()
method and store the result in a new OffsetDateTime
object. Finally, we print both the original and updated OffsetDateTime
objects.
Example 2:
OffsetDateTime dateTime = OffsetDateTime.of(2021, 10, 14, 16, 30, 45, 0, ZoneOffset.UTC);
System.out.println("Original OffsetDateTime: " + dateTime);
OffsetDateTime updatedDateTime = dateTime.minusYears(5);
System.out.println("Updated OffsetDateTime: " + updatedDateTime);
Output:
Original OffsetDateTime: 2021-10-14T16:30:45Z
Updated OffsetDateTime: 2016-10-14T16:30:45Z
In this example, we first create an OffsetDateTime
object representing a specific date and time using the of()
method. We then subtract 5 years from this object using the minusYears()
method and store the result in a new OffsetDateTime
object. Finally, we print both the original and updated OffsetDateTime
objects.