Java supports time formatting and parsing via pattern-based layouts, similar to other languages. The java.time package provides classes for handling date and time operations.
This Java code demonstrates various ways to format and parse dates and times. Here’s a breakdown of what’s happening:
We use ZonedDateTime.now() to get the current date and time with timezone information.
We format this time using the ISO_DATE_TIME formatter, which is similar to RFC3339.
We parse a string representation of a date and time using the same formatter.
We create custom formatters using DateTimeFormatter.ofPattern() to format the time in different ways.
We parse a time string using a custom formatter.
We use String.format() to create a custom numeric representation of the date and time.
Finally, we demonstrate error handling when parsing fails.
To run this program, save it as TimeFormattingParsing.java, compile it with javac TimeFormattingParsing.java, and run it with java TimeFormattingParsing.
The output will vary based on the current time when you run it, but it will demonstrate various formatted and parsed date-time representations.