Our first example demonstrates time formatting and parsing in Java using the java.time package, which provides a modern date-time API.
This Java code demonstrates various ways to format and parse dates and times. Here’s a breakdown of what’s happening:
We use LocalDateTime.now() to get the current date and time.
We format the current time using the ISO date-time formatter, which is similar to RFC3339.
We parse a specific date-time string using the ISO date-time formatter.
We create custom formatters using DateTimeFormatter.ofPattern() and use them to format the current time in various ways.
We demonstrate parsing a time string using a custom formatter.
We show how to format date-time components individually using String.format().
Finally, we show how parsing throws an exception when given malformed input.
Java’s java.time package provides a rich set of classes and methods for handling dates, times, and durations. The DateTimeFormatter class is particularly useful for creating custom date-time formats.
To run this program, save it as TimeFormattingParsing.java, compile it with javac TimeFormattingParsing.java, and then run it with java TimeFormattingParsing. The output will show various formatted date-times and parsing results.