Java LocalDateTime Class | format() Method with Example

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

LocalDateTime Class format() method

  • format() method is available in java.time package.
  • format() method is used to format this date-time object by using the given DateTimeFormatter.
  • 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 String formatted by the given formatter of this date-time object.

Example:

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

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

public class FormatOfLocalDateTime {
    public static void main(String args[]) {
        // Instantiates two LocalDateTime and
        // DateTimeFormatter
        LocalDateTime da_ti1 = LocalDateTime.parse("2005-10-05T10:10:10");
        LocalDateTime da_ti2 = LocalDateTime.now();
        DateTimeFormatter dtf1 = DateTimeFormatter.ofPattern("EEEE, MMM dd, yyyy HH:mm:ss a");
        DateTimeFormatter dtf2 = DateTimeFormatter.ofPattern("h:mm a");

        // Display da_ti1, da_ti2
        System.out.println("LocalDateTime da_ti1 and da_ti2: ");
        System.out.println("da_ti1: " + da_ti1);
        System.out.println("da_ti2: " + da_ti2);

        System.out.println();

        // Here, this method formats this date-time 
        // object by using the given DateTimeFormatter
        // i.e. here we are formatting da_ti1 by using
        // dtf1
        String format = da_ti1.format(dtf1);

        // Display format
        System.out.println("da_ti1.format(dtf1): " + format);

        // Here, this method formats this date-time 
        // object by using the given DateTimeFormatter
        // i.e. here we are formatting da_ti2 by using
        // dtf2
        format = da_ti2.format(dtf2);

        // Display format
        System.out.println("da_ti2.format(dtf2): " + format);
    }
}

Output

LocalDateTime da_ti1 and da_ti2: 
da_ti1: 2005-10-05T10:10:10
da_ti2: 2020-06-04T08:47:42.385488

da_ti1.format(dtf1): Wednesday, Oct 05, 2005 10:10:10 AM
da_ti2.format(dtf2): 8:47 AM


Comments and Discussions!

Load comments ↻





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