java.time.YearMonth.parse() Method Example



Description

The java.time.YearMonth.parse(CharSequence text, DateTimeFormatter formatter) method obtains an instance of YearMonth from a text string using a specific formatter.

Declaration

Following is the declaration for java.time.YearMonth.parse(CharSequence text, DateTimeFormatter formatter) method.

public static YearMonth parse(CharSequence text, DateTimeFormatter formatter)

Parameters

  • text − the text to parse such as "2017-12", not null.

  • formatter − the formatter to use, not null.

Return Value

the year-month, not null.

Exceptions

DateTimeParseException − if the text cannot be parsed.

Example

The following example shows the usage of java.time.YearMonth.parse(CharSequence text, DateTimeFormatter formatter) method.

package com.tutorialspoint;

import java.time.YearMonth;
import java.time.format.DateTimeFormatter;

public class YearMonthDemo {
   public static void main(String[] args) {
  
      DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yy-MM");
      String dateString = "17-12";
      YearMonth date = YearMonth.parse(dateString, dateTimeFormatter);
      System.out.println(date);
   }
}

Let us compile and run the above program, this will produce the following result −

2017-12
Advertisements