Saturday, November 22, 2025
HomeLanguagesJavaYearMonth parse(CharSequence) method in Java with Examples

YearMonth parse(CharSequence) method in Java with Examples

The parse(CharSequence) method of YearMonth class used to get an instance of YearMonth from a string such as ‘2018-12’ passed as parameter.The string must have a valid value that can be converted to a YearMonth object. The format of String must be uuuu-MM. YearMonths outside the range 0000 to 9999 must be prefixed by the plus or minus symbol.

Syntax:

public static YearMonth parse(CharSequence text)

Parameters:
This method accepts only one parameter text which represents the text to parse and format of this String must be like uuuu-MM.

Return value:
This method returns the parsed YearMonth.

Exception: This method throws following Exceptions:

  • DateTimeException – if the text cannot be parsed.

Below programs illustrate the parse(CharSequence text) method:

Program 1:




// Java program to demonstrate
// YearMonth.parse(CharSequence text) method
  
import java.time.*;
  
public class GFG {
    public static void main(String[] args)
    {
        // create a YearMonth object
        // using parse(CharSequence text)
        YearMonth yearMonth = YearMonth.parse("2019-12");
  
        // print instance
        System.out.println("YearMonth Parsed:"
                           + yearMonth);
    }
}


Output:

YearMonth Parsed:2019-12

Program 2:




// Java program to demonstrate
// YearMonth.parse(CharSequence text) method
  
import java.time.*;
  
public class GFG {
    public static void main(String[] args)
    {
        // create a YearMonth object
        // using parse(CharSequence text)
        YearMonth yearMonth = YearMonth.parse("2022-05");
  
        // print instance
        System.out.println("YearMonth Parsed:"
                           + yearMonth);
    }
}


Output:

YearMonth Parsed:2022-05

References:
https://docs.oracle.com/javase/10/docs/api/java/time/YearMonth.html#parse(java.lang.CharSequence)

Dominic
Dominichttp://wardslaus.com
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

Most Popular

Dominic
32407 POSTS0 COMMENTS
Milvus
97 POSTS0 COMMENTS
Nango Kala
6784 POSTS0 COMMENTS
Nicole Veronica
11930 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11999 POSTS0 COMMENTS
Shaida Kate Naidoo
6907 POSTS0 COMMENTS
Ted Musemwa
7168 POSTS0 COMMENTS
Thapelo Manthata
6863 POSTS0 COMMENTS
Umr Jansen
6847 POSTS0 COMMENTS