Java 8 – How to parse Instant in String form ?

In this article, we will learn how to parse an Instant given in String form using Instant.parse() method provided in Java 1.8 version

1. Parse java.time.Instant :

  • Instant provides a method called parse(String) which helps to parse a String to convert to an Instant
    • parse(CharSequence) – gets an instance of Instant from a text string such as 2007-12-03T10:15:30.00Z
  • The given String should be in either of the following formats, otherwise DateTimeParseException is thrown
    1. yyyy-MM-ddTHH:mm:ss.nnnZ
    2. yyyy-MM-ddTHH:mm:ssZ
  • Lets see an example to parse an Instant given in String-form

ParseInstantInString.java

package in.bench.resources.java8.instant.examples;

import java.time.Instant;

public class ParseInstantInString {

	public static void main(String[] args) {

		// 1. parse Instant in String-form - date(yyyy-MM-dd) & time(HH:mm:ss.nnn)
		Instant instant1 = Instant.parse("2022-08-21T05:33:45.191546200Z");
		System.out.println("Parsed Instant in (yyyy-MM-ddTHH:mm:ss.nnnZ) format is :- \n" 
				+ instant1);


		// 2. parse Instant in String-form - date(yyyy-MM-dd) & time(HH:mm:ss)
		Instant instant2 = Instant.parse("2022-08-23T17:23:54Z");
		System.out.print("\nParsed Instant in (yyyy-MM-ddTHH:mm:ssZ) format is :- \n" 
				+ instant2);
	}
}

Output:

Parsed Instant in (yyyy-MM-ddTHH:mm:ss.nnnZ) format is :- 
2022-08-21T05:33:45.191546200Z

Parsed Instant in (yyyy-MM-ddTHH:mm:ssZ) format is :- 
2022-08-23T17:23:54Z

2. DateTimeParseException thrown while parsing :

  • If the given String is in wrong format while parsing String to an Instant, then DateTimeParseException is thrown as shown in the below illustration

ParsingExceptionForWrongFormat.java

package in.bench.resources.java8.instant.examples;

import java.time.Instant;

public class ParsingExceptionForWrongFormat {

	public static void main(String[] args) {

		// 1. given String
		String str = "2022-08-23T17:23Z";


		// 2. parse Instant in String-form - wrong format
		Instant instant = Instant.parse(str);


		// 3. print to console
		System.out.print("\nParsed Instant (Date/time) "
				+ "in (yyyy-MM-ddTHH:mmZ) format is :- \n" 
				+ instant);
	}
}

Output:

Exception in thread "main" java.time.format.DateTimeParseException: 
Text '2022-08-23T17:23Z' could not be parsed at index 16
	at java.base/java.time.format.DateTimeFormatter.parseResolved0(DateTimeFormatter.java:2052)
	at java.base/java.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:1954)
	at java.base/java.time.Instant.parse(Instant.java:397)
	at in.bench.resources.java8.instant.examples.ParsingExceptionForWrongFormat
.main(ParsingExceptionForWrongFormat.java:14)

Related Articles:

References:

Happy Coding !!
Happy Learning !!

Java 8 – How to convert Instant to LocalDate ?
Java 8 – How to get Seconds and Nanoseconds from an Instant ?