Wednesday, July 3, 2024
HomeLanguagesJavaLocalTime format() method in Java with Examples

LocalTime format() method in Java with Examples

The format() method of a LocalTime class is used to format this time using the specified formatter passed as a parameter. This method formats this time based on passed formatter to a string.

Syntax:

public String format(DateTimeFormatter formatter)

Parameters: This method accepts a single parameter formatter which is the specified formatter. It should not be null.

Return value: This method returns the formatted time string.

Exception: This method throws a DateTimeException if an error occurs during printing.

Below programs illustrate the format() method:

Program 1:




// Java program to demonstrate
// LocalTime.format() method
  
import java.time.*;
import java.time.format.DateTimeFormatter;
  
public class GFG {
    public static void main(String[] args)
    {
  
        // create a LocalTime Objects
        LocalTime time
            = LocalTime.parse("03:18:23");
  
        // create formatter Object
        DateTimeFormatter formatter
            = DateTimeFormatter.ISO_TIME;
  
        // apply format
        String value = time.format(formatter);
  
        // print result
        System.out.println("value : "
                           + value);
    }
}


Output:

value : 03:18:23

Program 2:




// Java program to demonstrate
// LocalTime.format() method
  
import java.time.*;
import java.time.format.DateTimeFormatter;
  
public class GFG {
    public static void main(String[] args)
    {
  
        // create a LocalTime Objects
        LocalTime time
            = LocalTime.parse("23:59:59");
  
        // create formatter Object for ISO_LOCAL_TIME
        DateTimeFormatter formatter
            = DateTimeFormatter.ISO_LOCAL_TIME;
  
        // apply format
        String value = time.format(formatter);
  
        // print result
        System.out.println("value : "
                           + value);
    }
}


Output:

value : 23:59:59

Reference: https://docs.oracle.com/javase/10/docs/api/java/time/LocalTime.html#format(java.time.format.DateTimeFormatter)

Nokonwaba Nkukhwana
Experience as a skilled Java developer and proven expertise in using tools and technical developments to drive improvements throughout a entire software development life cycle. I have extensive industry and full life cycle experience in a java based environment, along with exceptional analytical, design and problem solving capabilities combined with excellent communication skills and ability to work alongside teams to define and refine new functionality. Currently working in springboot projects(microservices). Considering the fact that change is good, I am always keen to new challenges and growth to sharpen my skills.
RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments