BeginnersBook

  • Home
  • Java
    • Java OOPs
    • Java Collections
    • Java Examples
  • C
    • C Examples
  • C++
    • C++ Examples
  • DBMS
  • Computer Network
  • Python
    • Python Examples
  • More…
    • jQuery
    • Kotlin
    • WordPress
    • SEO
    • JSON
    • JSP
    • JSTL
    • Servlet
    • MongoDB
    • XML
    • Perl

Java YearMonth class explained with examples

By Chaitanya Singh | Filed Under: java

YearMonth class represents the date in combination of year and month such as 2022-06. This class does not store day, time or time-zone information. For example, the value “June 2022” can be stored in a YearMonth but the value “2nd June 2022” cannot be stored in a YearMonth.

Java YearMonth class:

public final class YearMonth extends Object
implements Temporal, TemporalAdjuster, Comparable<YearMonth>, Serializable

Java YearMonth class – Method Summary

MethodDescription
String format(DateTimeFormatter formatter)It formats this year-month using the specified formatter.
boolean isLeapYear()Checks if the year in this year-month is leap year or not. Returns true if the year is leap year else it returns false.
static YearMonth now()Obtains the current year-month from system in default time-zone.
static YearMonth of(int year, int month)Obtains an instance of YearMonth using the specified year and month information.
boolean equals(Object obj)Checks if this year-month is equal to the other year-month.
int compareTo(YearMonth other)Compares this year-month to another year month. Returns an integer value, which is 0 if both the year-month are equal. Negative if this year-month less than other year-month os Positive if this year-month greater than other year-month.
int get(TemporalField field)Gets the value of the specified field from this year-month.
LocalDate atEndOfMonth()Returns local date of end of the month.
YearMonth withMonth(int month)Returns a copy of this YearMonth after altering the month with the specified value.
YearMonth withYear(int year)Returns a copy of this YearMonth after altering the year with the spcified value.

Java YearMonth – now() & of() example

Method now() is used to get the current year-month data from the system in default time-zone. Method of() is used to specify the month and year info to get the YearMonth instance with the specified value.

import java.time.YearMonth;
public class JavaExample {
  public static void main(String[] args) {
    YearMonth yearMonth = YearMonth.now();
    System.out.println("Current Year Month: "+yearMonth);
    YearMonth yearMonth2 = YearMonth.of(2015, 8);
    System.out.println("Specified Year Month: "+yearMonth2);
  }
}  

Output:

Current Year Month: 2022-06
Specified Year Month: 2015-08

Java YearMonth – format example

To get the YearMonth in desired format, we can use the format() method of YearMonth class. We can specify the desired pattern and get the output in that particular format as shown in the following example.

import java.time.YearMonth;
import java.time.format.DateTimeFormatter;
public class JavaExample {
  public static void main(String[] args) {
    YearMonth yearMonth = YearMonth.now();
    String format = yearMonth.format(DateTimeFormatter.ofPattern("MM/yyyy"));
    String format2 = yearMonth.format(DateTimeFormatter.ofPattern("MM-yyyy"));
    String format3 = yearMonth.format(DateTimeFormatter.ofPattern("MM yyyy"));
    System.out.println("YearMonth in MM/yyyy format: "+format);
    System.out.println("YearMonth in MM-yyyy format: "+format2);
    System.out.println("YearMonth in MM/yyyy format: "+format3);
  }
}

Output:

YearMonth in MM/yyyy format: 06/2022
YearMonth in MM-yyyy format: 06-2022
YearMonth in MM/yyyy format: 06 2022

Java YearMonth – withYear(), equals(), isBefore() & isAfter() example

In this example, we have demonstrated the use of several methods of YearMonth class. The withYear() method is used to alter the year in the current year-month and the other comparison methods isEquals(), isBefore() and isAfter() are used to compare these two year-month instances.

import java.time.YearMonth;
public class JavaExample {
  public static void main(String[] args) {
    YearMonth yearMonth = YearMonth.now();
    System.out.println("Current year-month: "+yearMonth);
    YearMonth yearMonth2 = yearMonth.withYear(2015);
    System.out.println("Altered year-month: "+yearMonth2);
    System.out.println("Equals: "+yearMonth.equals(yearMonth2));
    System.out.println("isBefore: "+yearMonth.isBefore(yearMonth2));
    System.out.println("isAfter: "+yearMonth.isAfter(yearMonth2));
  }
}

Output:

Current year-month: 2022-06
Altered year-month: 2015-06
Equals: false
isBefore: false
isAfter: true

Java YearMonth – get() method example

We can use get() method to obtain the field value from this year-month.

import java.time.YearMonth;
import java.time.temporal.ChronoField;
public class JavaExample {
  public static void main(String[] args) {
    YearMonth yearMonth = YearMonth.now();
    System.out.println("Current Year Month: "+yearMonth);
    long year = yearMonth.get(ChronoField.YEAR);
    System.out.println(year);
    long month = yearMonth.get(ChronoField.MONTH_OF_YEAR);
    System.out.println(month);
  }
}

Output:

Current Year Month: 2022-06
2022
6

Java YearMonth – plus() & minus() example

We can add and remove specified amount of time from the YearMonth using plus() and minus() methods as shown in the following example.

import java.time.*;
public class JavaExample {
  public static void main(String[] args) {
    YearMonth yearMonth = YearMonth.now();
    System.out.println("Current Date: "+yearMonth);
    YearMonth yearMonth2 = yearMonth.plus(Period.ofYears(1));
    System.out.println("Current Date + 1 Year: "+yearMonth2);
    YearMonth yearMonth3 = yearMonth.minus(Period.ofMonths(6));
    System.out.println("Current Date - 6 Months: "+yearMonth3);
  }
}

Output:

Current Date: 2022-06
Current Date + 1 Year: 2023-06
Current Date - 6 Months: 2021-12
❮ Java Tutorial

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Java Tutorial

Java Introduction

  • Java Index
  • Java Introduction
  • History of Java
  • Features of Java
  • C++ vs Java
  • JDK vs JRE vs JVM
  • JVM - Java Virtual Machine
  • First Java Program
  • Variables
  • Data Types
  • Operators

Java Flow Control

  • Java If-else
  • Java Switch-Case
  • Java For loop
  • Java while loop
  • Java do-while loop
  • Continue statement
  • break statement

Java Arrays

  • Java Arrays

OOPs Concepts

  • OOPs Concepts
  • Constructor
  • Java String
  • Static keyword
  • Inheritance
  • Types of inheritance
  • Aggregation
  • Association
  • Super Keyword
  • Method overloading
  • Method overriding
  • Overloading vs Overriding
  • Polymorphism
  • Types of polymorphism
  • Static and dynamic binding
  • Abstract class and methods
  • Interface
  • Abstract class vs interface
  • Encapsulation
  • Packages
  • Access modifiers
  • Garbage Collection
  • Inner classes
  • Static import
  • Static constructor

Java Exception Handling

  • Exception handling
  • Java try-catch
  • Java throw
  • Java throws
  • Checked and Unchecked Exceptions
  • Jav try catch finally
  • Exception Examples
  • Exception Propagation

Collections Framework

  • Collections in Java
  • Java ArrayList
  • Java LinkedList
  • Java Vector
  • Java HashSet
  • Java LinkedHashSet
  • Java TreeSet
  • Java HashMap
  • Java TreeMap
  • Java LinkedHashMap
  • Java Queue
  • Java PriorityQueue
  • Java Deque
  • Comparable interface
  • Comparator interface
  • Collections Interview Questions

MORE ...

  • Java Scanner Class
  • Java 8 Features
  • Java 9 Features
  • Java Conversion
  • Java Date
  • Java Multithreading
  • Java I/O
  • Java Serialization
  • Java Regex
  • Java AWT
  • Java Swing
  • Java Enum
  • Java Annotations
  • Java main method
  • Java Interview Q

Copyright © 2012 – 2022 BeginnersBook . Privacy Policy . Sitemap