Expand Authors Top

If you have a few years of experience in the Java ecosystem and you’d like to share that with the community, have a look at our Contribution Guidelines.

Expanded Audience – Frontegg – Security (partner)
announcement - icon User management is very complex, when implemented properly. No surprise here.

Not having to roll all of that out manually, but instead integrating a mature, fully-fledged solution - yeah, that makes a lot of sense.
That's basically what Frontegg is - User Management for your application. It's focused on making your app scalable, secure and enjoyable for your users.
From signup to authentication, it supports simple scenarios all the way to complex and custom application logic.

Have a look:

>> Elegant User Management, Tailor-made for B2B SaaS

Java Top

Get started with Spring 5 and Spring Boot 2, through the Learn Spring course:

> CHECK OUT THE COURSE

1. Overview

In this tutorial, we'll learn how to format an instant to a String in Java.

First, we'll start with a bit of background about what an instant is in Java. Then we'll demonstrate how to answer our central question using core Java and third-party libraries, such as Joda-Time.

2. Formatting Instant Using Core Java

According to the Java documentation, an instant is a measured timestamp from the Java epoch of 1970-01-01T00:00:00Z.

Java 8 contains a handy class called Instant to represent a specific instantaneous point on the timeline. Typically, we can use this class to record event timestamps in our applications.

Now that we know what an instant is in Java, let's see how we can convert it into a String object.

2.1. Using the DateTimeFormatter Class

Generally speaking, we'll need a formatter to format an Instant object. Fortunately for us, Java 8 introduced the DateTimeFormatter class to uniformly format dates and times.

Basically, DateTimeFormatter provides the format() method to do the job.

Simply put, DateTimeFormatter requires a time zone to format an instant. Without it, it'll fail to convert the instant to human-readable date/time fields.

For instance, let's suppose we want to display our Instant instance using the dd.MM.yyyy format:

public class FormatInstantUnitTest {
    
    private static final String PATTERN_FORMAT = "dd.MM.yyyy";

    @Test
    public void givenInstant_whenUsingDateTimeFormatter_thenFormat() {
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern(PATTERN_FORMAT)
            .withZone(ZoneId.systemDefault());

        Instant instant = Instant.parse("2022-02-15T18:35:24.00Z");
        String formattedInstant = formatter.format(instant);

        assertThat(formattedInstant).isEqualTo("15.02.2022");
    }
    ...
}

As shown above, we can use the withZone() method to specify the time zone.

Please bear in mind that failing to specify a time zone will lead to an UnsupportedTemporalTypeException:

@Test(expected = UnsupportedTemporalTypeException.class)
public void givenInstant_whenNotSpecifyingTimeZone_thenThrowException() {
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern(PATTERN_FORMAT);

    Instant instant = Instant.now();
    formatter.format(instant);
}

2.2. Using the toString() Method

Another solution is to use the toString() method to get the string representation of the Instant object.

Let's exemplify the use of the toString() method using a test case:

@Test
public void givenInstant_whenUsingToString_thenFormat() {
    Instant instant = Instant.ofEpochMilli(1641828224000L);
    String formattedInstant = instant.toString();

    assertThat(formattedInstant).isEqualTo("2022-01-10T15:23:44Z");
}

The limitation of this approach is that we can't use a custom, human-friendly format to display the instant.

3. Joda-Time Library

Alternatively, we can use the Joda-Time API to achieve the same objective. This library provides a set of ready-to-use classes and interfaces for manipulating the date and time in Java.

Among these classes, we'll find the DateTimeFormat class. As the name implies, this class can be used to format or parse date/time data to and from a string.

Let's illustrate how to use DateTimeFormatter to convert an instant into a string:

@Test
public void givenInstant_whenUsingJodaTime_thenFormat() {
    org.joda.time.Instant instant = new org.joda.time.Instant("2022-03-20T10:11:12");
        
    String formattedInstant = DateTimeFormat.forPattern(PATTERN_FORMAT)
        .print(instant);

    assertThat(formattedInstant).isEqualTo("20.03.2022");
}

As we can see, DateTimeFormatter provides forPattern() to specify the formatting pattern, and print() to format the Instant object.

4. Conclusion

In this article, we covered in-depth how to format an instant to a string in Java.

We explored a couple of ways to achieve this using core Java methods. Then we explained how to accomplish the same thing using the Joda-Time library.

As always, the code used in this article can be found over on GitHub.

Java bottom

Get started with Spring 5 and Spring Boot 2, through the Learn Spring course:

>> CHECK OUT THE COURSE
Generic footer banner
Comments are closed on this article!