Skip to content
Related Articles

Related Articles

MonthDay parse(CharSequence, DateTimeFormatter) method in Java

View Discussion
Improve Article
Save Article
  • Last Updated : 12 May, 2020

The parse(CharSequence text, DateTimeFormatter formatter) method of the MonthDay class in Java is used to get an instance of MonthDay from a text string using a specific formatter.
Syntax:

public static MonthDay parse(
    CharSequence text, 
    DateTimeFormatter formatter)

Parameters: This method accepts

  • text as a parameter to parse and
  • formatter as a parameter to use.

Return value: This method returns the parsed month-day.

Exceptions: This method throws DateTimeParseException if the text cannot be parsed.

Below programs illustrate the parse(CharSequence text, DateTimeFormatter formatter) method of MonthDay in Java:

Program 1:




// Java program to demonstrate
// MonthDay.parse(CharSequence text,
// DateTimeFormatter formatter) method
  
import java.time.*;
import java.time.temporal.*;
import java.time.format.*;
  
public class GFG {
    public static void main(String[] args)
    {
  
        // apply ofpattern() method
        // of DateTimeFormatter class
        DateTimeFormatter datetimeformatter
            = DateTimeFormatter.ofPattern("--MM-dd");
  
        // apply parse(CharSequence text,
        // DateTimeFormatter formatter) method
        // of MonthDay class
        MonthDay monthday = MonthDay.parse(
            "--05-09", datetimeformatter);
  
        // print monthday
        // in mm-dd format
        System.out.println("MonthDay: "
                           + monthday);
    }
}

Output:

MonthDay: --05-09

Program 2:




// Java program to demonstrate
// MonthDay.parse(CharSequence text,
// DateTimeFormatter formatter) method
  
import java.time.*;
import java.time.temporal.*;
import java.time.format.*;
  
public class GFG {
    public static void main(String[] args)
    {
  
        // apply ofpattern() method
        // of DateTimeFormatter class
        DateTimeFormatter datetimeformatter
            = DateTimeFormatter.ofPattern("--dd-MM");
  
        // apply parse(CharSequence text,
        // DateTimeFormatter formatter) method
        // of MonthDay class
        MonthDay monthday = MonthDay.parse(
            "--05-09", datetimeformatter);
  
        // print monthday
        // in dd-mm format
        System.out.println("MonthDay: "
                           + monthday);
    }
}

Output:

MonthDay: --09-05

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


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!