Format an Instant to a String in Java

06 May 2023 Balmiki Mandal 0 Core Java

Formatting Instant to String in Java

In this article, we will discuss how to format an instance of java.time.Instant to a string in Java. The instant class is part of the java.time package that was introduced in Java 8 and provides a way to represent a point in time in a precise way. We can use the DateTimeFormatter class to format the instant object into different format strings. Let's take a look at some examples.

Using Default Formatters

The Java 8 DateTimeFormatter contains some predefined formatters which allow us to easily format the Instant to a string representation. Here is an example of how to format an instant to ISO_DATE_TIME format:

DateTimeFormatter formatter = DateTimeFormatter.ISO_DATE_TIME;
String dateTimeString = formatter.format(Instant.now());
System.out.println(dateTimeString);

This will print out a string in the format "yyyy-MM-dd'T'HH:mm:ss.SSSZ". If you want to go further and customize the format of the string, then you can create your own formatter with the DateTimeFormatter.ofPattern method.

Creating Custom Formatters

To create a custom formatter for an instant, we need to create an instance of the DateTimeFormatter class. We can do this using the ofPattern method which takes a string argument that defines the desired format of the string. For example, if we wanted to format an instant into a date-time string in the format "yyyy-MM-dd HH:mm:ss", then we can do the following:

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
String dateTimeString = formatter.format(Instant.now());
System.out.println(dateTimeString);

This will print out a string in the desired format.

In this article, we discussed how to format an instant to a string in Java using the DateTimeFormatter class. We looked at using the default formatters as well as creating custom formatters for different types of string representations.

BY: Balmiki Mandal

Related Blogs

Post Comments.

Login to Post a Comment

No comments yet, Be the first to comment.