Thursday, January 22, 2026
HomeLanguagesJavaYear parse(CharSequence,DateTimeFormatter) method in Java with Examples

Year parse(CharSequence,DateTimeFormatter) method in Java with Examples

The Year.parse(CharSequence, DateTimeFormatter) method of Year class is used to get an instance of Year from a string such as ‘2018’ passed as parameter using a specificDateTimeFormatter.The Year is parsed using a specific DateTimeFormatter. The string must have a valid value that can be converted to a Year. Years outside the range 0000 to 9999 must be prefixed by the plus or minus symbol. Syntax:

public static Year parse(CharSequence text,
                         DateTimeFormatter formatter)

Parameters: This method accepts two parameters text which represents the text to parse such as “2021” and formatter which represents the formatter to use. Return value: This method returns the parsed year. Exception: This method throws following Exceptions:

  • DateTimeException – if the text cannot be parsed.

Below programs illustrate the parse(CharSequence, DateTimeFormatter) method: Program 1: 

Java




// Java program to demonstrate
// Year.parse(CharSequence, DateTimeFormatter) method
 
import java.time.*;
import java.time.format.*;
 
public class GFG {
    public static void main(String[] args)
    {
        // create a formatter
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yy");
 
        // create a Year object
        // using parse(CharSequence, DateTimeFormatter)
        Year year = Year.parse("18", formatter);
 
        // print instance
        System.out.println("Year Parsed:"
                           + year);
    }
}


Output:

Year Parsed:2018

Program 2: 

Java




// Java program to demonstrate
// Year.parse(CharSequence, formatter) method
 
import java.time.*;
import java.time.format.*;
 
public class GFG {
    public static void main(String[] args)
    {
        // create a formatter
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy");
 
        // create a Year object
        // using parse(CharSequence, DateTimeFormatter)
        Year year = Year.parse("2087", formatter);
 
        // print instance
        System.out.println("Year Parsed:"
                           + year);
    }
}


Output:

Year Parsed:2087

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

RELATED ARTICLES

1 COMMENT

Most Popular

Dominic
32475 POSTS0 COMMENTS
Milvus
119 POSTS0 COMMENTS
Nango Kala
6847 POSTS0 COMMENTS
Nicole Veronica
11977 POSTS0 COMMENTS
Nokonwaba Nkukhwana
12064 POSTS0 COMMENTS
Shaida Kate Naidoo
6986 POSTS0 COMMENTS
Ted Musemwa
7220 POSTS0 COMMENTS
Thapelo Manthata
6933 POSTS0 COMMENTS
Umr Jansen
6912 POSTS0 COMMENTS