OffsetDateTime format() method in Java with examples

The OffsetDateTime class in Java uses the formatter that has been provided to format this date and time in its format() method. The OffsetDateTime class in Java uses the formatter that has been provided to format this date and time in its format() method.

Syntax:

Parameter: This method only takes the formatter parameter, which is the formatter to use that does not take null.

Return Value: The formatted date string is returned, not null.

Exceptions: An error during printing is handled by the function by throwing a DateTimeException.

Example 1:

The Java code that is given shows us how to parse and gather an OffsetDateTime object. Prior to defining a class called formatExample1 with a main function, it imports the required classes. A provided date-time string is parsed inside the main method to construct an OffsetDateTime instance d1. Next, the date and time are parsed and printed to the terminal. Next, the ISO_TIME format is used to define an instance format for DateTimeFormatter. Using the ISO_TIME formatter, the code finally forms the OffsetDateTime instance d1 and outputs the formatted time.

Implementation:

FileName: formatExample1.java

Output:

 
The Date is given by: 2018-12-12T13:30:30+05:00
The format is given by: 13:30:30+05:00   

Example 2:

A class named formatExample2 is defined in the Java code, and its main method shows how to parse and format an OffsetDateTime object. It attempts to parse a given date-time string into an OffsetDateTime instance d1 inside of a try-catch block. If parsing is successful, the formatted time is printed to the terminal along with the parsed date and time, which has been formatted using the ISO_TIME formatter. But the date string has an illegal month value ("13"). As a result, a DateTimeParseException is generated, taken in, and the exception message is written to the console.

Implementation:

FileName: formatExample2.java

Output:

 
java.time.format.DateTimeParseException: Text '2024-13-27T13:30:30+05:00' could not be parsed: Invalid value for MonthOfYear (valid values 1 - 12): 13