Java LocalDate Class | format() Method with Example

LocalDate Class format() method: Here, we are going to learn about the format() method of LocalDate Class with its syntax and example.
Submitted by Preeti Jain, on May 29, 2020

LocalDate Class format() method

  • format() method is available in java.time package.
  • format() method is used to format this LocalDate object by using the given DateTimeFormatter object.
  • format() method is a non-static method, it is accessible with the class object only and if we try to access the method with the class name then we will get an error.
  • format() method may throw an exception at the time of formatting this object.
    DateTimeException: This exception may throw when getting any error during formatting.

Syntax:

    public String format(DateTimeFormatter dt_formatter);

Parameter(s):

  • DateTimeFormatter dt_formatter – represents the formatter to format this object.

Return value:

The return type of this method is String, it returns date formatted by the given formatter of this LocalDate object.

Example:

// Java program to demonstrate the example 
// of format(DateTimeFormatter dt_formatter)
// method of LocalDate

import java.time.*;
import java.time.format.*;

public class FormatOfLocalDate {
    public static void main(String args[]) {
        // Instantiates two LocalDate
        LocalDate l_da1 = LocalDate.parse("2007-04-04");
        LocalDate l_da2 = LocalDate.now();

        // Display l_da1,l_da2
        System.out.println("LocalDate l_da1 and l_da2: ");
        System.out.println("l_da1: " + l_da1);
        System.out.println("l_da2: " + l_da2);

        System.out.println();

        // Here, this method formats this date 
        // by using the pattern "dd-MMM-yyyy"

        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("dd-MMM-yyyy");
        String format = l_da1.format(dtf);

        // Display format
        System.out.println("l_da1.format(dtf): " + format);

        // Here, this method formats this date by
        // using the pattern "dd/MM/yyyy"

        dtf = DateTimeFormatter.ofPattern("dd/MM/yyyy");
        format = l_da2.format(dtf);

        // Display format
        System.out.println("l_da2.format(dtf): " + format);
    }
}

Output

LocalDate l_da1 and l_da2: 
l_da1: 2007-04-04
l_da2: 2020-05-29

l_da1.format(dtf): 04-Apr-2007
l_da2.format(dtf): 29/05/2020


Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.