Time formatting and parsing in Java is handled primarily through the java.time package, which provides a rich set of classes for working with dates and times.
In Java, time formatting and parsing are handled through the java.time package, which provides a more comprehensive and flexible API compared to older date-time classes.
The DateTimeFormatter class is the main tool for formatting and parsing date-time objects. It offers both predefined formats (like ISO_DATE_TIME) and the ability to create custom formats using patterns.
For parsing, you typically use the parse method of the appropriate date-time class (like ZonedDateTime or LocalDateTime), passing in both the string to parse and the formatter to use.
Java’s date-time API doesn’t use example-based layouts like Go. Instead, you define patterns using letters to represent different components of a date or time. For example, ‘yyyy’ represents a 4-digit year, ‘MM’ a 2-digit month, ‘dd’ a 2-digit day, and so on.
When parsing fails due to malformed input, a DateTimeParseException is thrown, which you can catch to handle the error.
Remember to handle potential exceptions when parsing dates, as shown in the last example.
This Java code demonstrates equivalent functionality to the original example, showcasing how to format and parse times in various ways using Java’s date-time API.