Our first program will demonstrate time formatting and parsing in Java. Here’s the full source code:
This program demonstrates various ways to format and parse dates and times in Java using the java.time package, which was introduced in Java 8.
Here’s a breakdown of what the code does:
We start by formatting the current time using the ISO_DATE_TIME formatter, which is similar to RFC3339.
We then parse a specific date-time string using the same formatter.
We demonstrate how to create custom formatters using pattern strings. These patterns use specific letters to represent different parts of a date or time.
We show how to parse a time string using a custom formatter.
We use String.format to create a purely numeric representation of the current time.
Finally, we show how parsing can throw a DateTimeParseException when given malformed input.
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 vary depending on the current time when you run it, but it will look something like this:
This example showcases Java’s powerful date and time manipulation capabilities, which are more type-safe and less error-prone than the older java.util.Date and java.util.Calendar classes.