MonthDay format() method in Java


The MonthDay can be formatted with the specified formatter using the format() method in the MonthDay class in Java. This method requires a single parameter i.e. the MonthDay object to be formatted and it returns the formatted MonthDay with the specified formatter.

A program that demonstrates this is given as follows

Example

 Live Demo

import java.time.*;
import java.time.temporal.*;
import java.time.format.DateTimeFormatter;
   public class Demo {
      public static void main(String[] args) {
      MonthDay md = MonthDay.parse("--02-22");
      LocalDate ld = md.atYear(2019);
      System.out.println("The MonthDay is: " + md);
      DateTimeFormatter dtf = DateTimeFormatter.ofPattern("YYYY-MM-dd");
      System.out.println("The formatted MonthDay is: " + dtf.format(ld));
   }
}

Output

The MonthDay is: --02-22
The formatted MonthDay is: 2019-02-22

Now let us understand the above program.

First the MonthDay is displayed. Then the MonthDay is formatted with the specified formatter using the format() method and the formatted MonthDay is displayed. A code snippet that demonstrates this is as follows:

MonthDay md = MonthDay.parse("--02-22");
LocalDate ld = md.atYear(2019);
System.out.println("The MonthDay is: " + md);
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("YYYY-MM-dd");
System.out.println("The formatted MonthDay is: " + dtf.format(ld));

Updated on: 30-Jul-2019

51 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements