Java supports time formatting and parsing via pattern-based layouts, similar to other programming languages. We’ll use the java.time package for this example.
In Java, we use the java.time package for date and time operations. The DateTimeFormatter class is used for parsing and formatting dates and times.
We start by getting the current time using ZonedDateTime.now() and formatting it using the ISO_DATE_TIME formatter, which is similar to RFC3339.
For parsing, we use the same DateTimeFormatter with the parse method of ZonedDateTime.
Java provides several predefined formatters, and we can also create custom ones using patterns. The ofPattern method allows us to define custom formats.
For purely numeric representations, we can use String.format or System.out.printf with the extracted components of the time value.
When parsing fails due to malformed input, Java throws a DateTimeParseException. We catch this exception to demonstrate error handling.
To run this program, save it as TimeFormattingParsing.java, compile it with javac TimeFormattingParsing.java, and run it with java TimeFormattingParsing. The output will show various formatted dates and times, along with examples of parsing.