Java ChronoLocalDate format(DateTimeFormatter formatter)

PreviousNext

The format() method of ChronoLocalDate interface formats this date using the specified formatter.

Syntax:

public String format(DateTimeFormatter formatter)

Parameter: obj which specifies the formatter to be used.

Return Value: It returns the formatted date string.

Example

The following code shows how to use format() method of ChronoLocalDate in Java:

// Program to illustrate the format() method

import java.util.*;
import java.time.*;
import java.time.chrono.*;
import java.time.format.DateTimeFormatter;

public class Main {
    public static void main(String[] args) {

        // Parses the date
        ChronoLocalDate dt = LocalDate.parse("2018-11-01");
        System.out.println(dt);

        // Function call
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd/MM/YYYY");

        System.out.println(formatter.format(dt));
    }
}

Result

Another example: To illustrate the exception.

Program to illustrate the format() method Exception Program

import java.util.*;
import java.time.*;
import java.time.chrono.*;
import java.time.format.DateTimeFormatter;

public class Main {
    public static void main(String[] args) {
        try {/*w  w    w  .d    em   o  2  s   . c   om  */
            // Parses the date
            ChronoLocalDate dt = LocalDate.parse("2018-01-32");
            System.out.println(dt);

            // Function call
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd/MM/YYYY");

            System.out.println(formatter.format(dt));
        } catch (Exception e) {
            System.out.println(e);
        }
    }
}

Result

PreviousNext

Related