Format a date using the new date time API
System Design practice on Codemia
Work through 120+ system design problems with detailed solutions, from rate limiters to multi-region storage.
In recent years, formatting dates in Java has significantly improved with the introduction of the new Date-Time API in Java 8. The new API provides a more comprehensive and flexible way to handle dates, eliminating many of the problems associated with the older java.util.Date and java.util.Calendar classes.
Understanding the New Date-Time API
The new Date-Time API is part of the java.time package and addresses several issues with the legacy date-time APIs, such as thread safety and lack of proper timezone support. The most commonly used classes in this package include:
LocalDate: Represents a date without a time zone, such as 2023-10-10.LocalTime: Represents a time without a time zone, such as 13:45.LocalDateTime: Represents both date and time without a time zone, such as 2023-10-10T13:45.ZonedDateTime: Represents date and time with a time zone, such as 2023-10-10T13:45+01:00[Europe/London].
Basic Date Formatting
To format a date into a specific style, the DateTimeFormatter class is used. This class offers various built-in formatters and also allows for the creation of custom format patterns.
Pre-Defined Formatters
The DateTimeFormatter class includes several pre-defined constants for common patterns, making it easy to handle common formatting scenarios:
DateTimeFormatter.ISO_LOCAL_DATE:yyyy-MM-ddDateTimeFormatter.ISO_DATE:yyyy-MM-dd+HH:mm:ssDateTimeFormatter.BASIC_ISO_DATE:yyyyMMddDateTimeFormatter.ISO_DATE_TIME:yyyy-MM-dd'T'HH:mm:ss.SSSZ
Here is an example using one of these pre-defined formatters:
Custom Format Patterns
For custom date formatting, you can define a pattern string specific to your requirements. This pattern can include symbols like y, M, d, H, m, s, S, and others.
y: YearM: Monthd: Day of the monthH: Hour (24-hour clock)m: Minutes: SecondS: Fraction of second
Example of using a custom pattern:
Parsing Dates
Apart from formatting, DateTimeFormatter can also parse a string into a date-time object. It’s crucial to use a pattern that matches the input string.
Key Advantages of the New Date-Time API
The table below summarizes some of the most significant improvements offered by the new API:
| Feature | Description |
| Immutable Objects | Date-time classes like LocalDate and LocalDateTime are immutable and thread-safe, providing a safer approach in multi-threaded contexts. |
| Comprehensive Zone Support | Offers sophisticated support for time zones, offsets, daylight saving time automatically, with classes like ZonedDateTime. |
| Flexibility and Precision | Allows for detailed and precise date and time calculations, with classes for various temporal units and clear distinction between them. |
| Fluent API | The API supports a fluent programming style, making it more readable and expressive while chaining multiple operations. |
Additional Details and Resources
- Period and Duration: Beyond just dates and times, the API provides
Periodfor years, months, and days, andDurationfor hours, minutes, and seconds. - Temporal Adjusters: A powerful set of utility methods to perform complex date-time manipulations, like finding the next weekday.
- Backward Compatibility: While the
java.timepackage is modern and robust, Java provides mechanisms likeDate.from(Instant)andDate.toInstant()to interoperate with legacy code.
The new Date-Time API is a significant leap forward in terms of functionality and ease of use in Java. Whether it’s handling internationalization, time zones, or simply formatting a date in a native style, this API equips developers with robust tools, resulting in cleaner, safer, and more comprehensible code.
Related reading
- Formatting IPv6 as an int in C and storing it in SQL Server
- Forward host port to docker container
- Forward HTTPS client ip from Google Container Engine
- From inside of a Docker container, how do I connect to the localhost of the machine?
- Formatting date in Thymeleaf
- Found multiple occurrences of org.json.JSONObject on the class path
- Frontend communication with API in Kubernetes cluster
- GCE ingress with routes always falls back to default-http-backend

System Design Fundamentals
Build a strong foundation in designing scalable, reliable distributed systems.
View the courseTrack what you have practised
A free account saves your progress, solutions and study plan across every problem on Codemia.
System Design practice on Codemia
Work through 120+ system design problems with detailed solutions, from rate limiters to multi-region storage.