YearMonth minus(long,unit) method in Java with Examples

The minus(long, unit) method of YearMonth class is used to return a copy of this Year-month after subtracting the specified amount of TemporalUnit from this Year-month object.An exception is thrown, If the specified unit cannot be subtracted from Year-month. This instance is immutable and unaffected by this method call.
Syntax:
public YearMonth minus(long amountToSubtract, TemporalUnit unit)
Parameters: This method accepts two parameters:
- amountToSubtract: This parameter represents the amount of the unit to subtract from the result.
- unit: This parameter represents the unit of the amount to subtract.
Return Value: This method returns a Year-month based on this Year-month with the specified amount subtracted.
Exception: This method throws following Exceptions:
- DateTimeException – This exception is thrown if the subtraction cannot be made.
- UnsupportedTemporalTypeException – This exception is thrown if the unit is not supported.
- ArithmeticException – This exception is thrown if numeric overflow occurs.
Below programs illustrate the minus(long, unit) method:
Program 1:
// Java program to demonstrate// YearMonth.minus(long, unit) method import java.time.*;import java.time.temporal.*; public class GFG { public static void main(String[] args) { // Create a YearMonth object YearMonth thisYearMonth = YearMonth.of(2017, 8); // print instance System.out.println("YearMonth :" + thisYearMonth); // apply minus(long, unit) method // subtracting 20 Years YearMonth value = thisYearMonth.minus(20, ChronoUnit.YEARS); // print result System.out.println("After subtraction YearMonth: " + value); }} |
Output:
YearMonth :2017-08 After subtraction YearMonth: 1997-08
Program 2:
// Java program to demonstrate// YearMonth.minus(long, unit) method import java.time.*;import java.time.temporal.*; public class GFG { public static void main(String[] args) { // Create a YearMonth object YearMonth thisYearMonth = YearMonth.of(2019, 12); // print instance System.out.println("YearMonth :" + thisYearMonth); // apply minus(long, unit) method // subtracting 30 Months YearMonth value = thisYearMonth.minus(30, ChronoUnit.MONTHS); // print result System.out.println("After subtraction YearMonth: " + value); }} |
Output:
YearMonth :2019-12 After subtraction YearMonth: 2017-06



