Table of Contents
1. Introduction
In Java, dealing with date and time is a common requirement in many applications. One specific task is formatting an Instant object to a String. An Instant represents a specific moment on the timeline in UTC. The goal is to convert this Instant into a human-readable date and time format as a String.
In this article, we will explore various methods to format an Instant to String in Java, compare their usability, and detail each approach to cover different scenarios.
2. Using DateTimeFormatter Class
Instant does not contain time zone information, it only have timestamp to milliseconds from UNIX epoch i.e 1 Jan 1970 from UTC,so DateTimeFormatter
can not print date directly because date is always printed with time zone information.
In order to format Instant to String, we need to first associate timezone to formatter and it will work fine.
Get current timestamp in java
1 2 3 4 5 6 7 |
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss") .withZone(ZoneId.systemDefault()); Instant instant = Instant.now(); String instantStr = formatter.format( instant ); System.out.println("Instant in String format: "+instantStr); |
Output:
DateTimeFormatter.ofPattern(String): Defines the pattern to format the date and time.
.withZone(ZoneId): Sets the time zone to use, here the system’s default time zone.
formatter.format(Instant): Formats the given Instant according to the defined pattern and time zone.
This method is versatile and recommended for most use cases, especially where custom date-time formats are required.
If we do not provide timezone information, then DateTimeFormatter
will through an Exception.
1 2 3 4 5 6 7 |
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); Instant instant = Instant.now(); String instantStr = formatter.format(instant); System.out.println("Instant in String format: "+instantStr); |
Output:
at java.base/java.time.Instant.getLong(Instant.java:603)
at java.base/java.time.format.DateTimePrintContext.getValue(DateTimePrintContext.java:308)
at java.base/java.time.format.DateTimeFormatterBuilder$NumberPrinterParser.format(DateTimeFormatterBuilder.java:2704)
at java.base/java.time.format.DateTimeFormatterBuilder$CompositePrinterParser.format(DateTimeFormatterBuilder.java:2343)
at java.base/java.time.format.DateTimeFormatter.formatTo(DateTimeFormatter.java:1848)
at java.base/java.time.format.DateTimeFormatter.format(DateTimeFormatter.java:1822)
at org.arpit.java2blog.entry.FormatInstantToString.main(FormatInstantToString.java:15)
Further reading:
2.1 Using DateTimeFormatter in ISO-8601 format
We can use DateTimeFormatter
with ISO_LOCAL_DATE_TIME
to print String in ISO-8601 format.
1 2 3 4 5 6 7 8 |
DateTimeFormatter formatter = DateTimeFormatter.ISO_LOCAL_DATE_TIME .withZone(ZoneId.from(ZoneOffset.UTC)); Instant instant = Instant.now(); String instantStr = formatter.format(instant); System.out.println("Instant in String format: "+instantStr); |
Output:
3. Using Instant’s toString() Method
Instants are already in UTC and if we are not worried about format, then we can simply use toString()
method. Instant’s toString() method converts the Instant to an ISO-8601 string representation.
1 2 3 4 5 |
Instant instant = Instant.now(); String instantStr = instant.toString(); System.out.println("Default String format for Instant: "+instantStr); |
Output:
if we don’t want T and Z in the String. we can change highlighted line to:
1 2 3 4 |
String instantStr = instant.toString().replaceAll("[TZ]", " "); // Output: Default String format for Instant: 2021-05-01 12:14:30.687870800 |
If we need time in milliseconds rather than nanosecond, we can use:
1 2 3 4 |
String instantStr = instant.truncatedTo(ChronoUnit.MILLIS).toString().replaceAll("[TZ]", " ") // Output: Default String format for Instant: 2021-05-01 12:15:12.073 |
This method is straightforward and useful when the ISO-8601 format is acceptable. It requires no additional formatting.
4. Using Date.from(Instant) and SimpleDateFormat
The idea is to convert Instant to java.util.Date
using Date.from(Instant)
and then format it using SimpleDateFormat
.
1 2 3 4 5 6 7 |
Instant instant = Instant.now(); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); Date date = Date.from(instant); System.out.println(sdf.format(date)); // Output : 2023-11-21 12:31:38 |
This method is suitable for applications that still use the older java.util.Date
class, providing a bridge between the old and new Date-Time APIs.
5. Conclusion
Formatting an Instant to a String in Java can be achieved through various methods, each serving different needs.
The DateTimeFormatter
approach is the most flexible and aligns with the modern Java Date-Time API, making it the preferred choice. The built-in toString()
method of Instant is convenient for standard ISO-8601 formats, while the SimpleDateFormat
approach is useful for legacy applications.