Java 8 – How to convert Instant to java.util.Date and vice-versa ?

In this article, we will learn how to convert Instant to java.util.Date & vice-versa using newly introduced methods in Date class in Java 1.8 version

Date class in Java 1.8 version :

  • There are 2 new methods introduced in Java 1.8 version for Date class, those are
    1. from(Instant) – This static method obtains an instance of Date from an Instant object
    2. toInstant() – This method converts invoking Date object to an Instant
  • Note: Many legacy methods of Date class are deprecated

1. Convert Instant to java.util.Date :

  • Converting Instant to Date is very straightforward as,
    • Date.from() method accepts Instant as inputargument and returns java.util.Date
  • Converted java.util.Date will have,
    • Date & Time & Offset/Zone parts shifted to that particular Zone from the given Instant
  • In short, Instant -> java.util.Date
  • Lets see an example for conversion of Instant to java.util.Date in the below illustration

ConvertInstantToJavaUtilDate.java

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

import java.time.Instant;
import java.util.Date;

public class ConvertInstantToJavaUtilDate {

	public static void main(String[] args) {

		// get instantaneous moment at UTC/GMT
		Instant instant = Instant.now();
		System.out.println("Current Instant at UTC/GMT is :- \n" 
				+ instant);


		// convert Instant to Date
		Date date = Date.from(instant);
		System.out.print("\nConversion of Instant to Date is :- \n" 
				+ date);
	}
}

Output:

Current Instant at UTC/GMT is :- 
2022-08-20T12:24:54.025585200Z

Conversion of Instant to Date is :- 
Sat Aug 20 17:54:54 IST 2022

2. Convert java.util.Date to an Instant :

  • Get java.util.Date instantiating Date object for conversion to an Instant
  • Conversion steps
    1. Convert Date to Instant using toInstant() method
  • In short, java.util.Date -> Instant
  • Read Java 8 – How to convert java.util.Date to an Instant in different ways ? for more details and examples
  • Lets see an example for conversion of java.util.Date to an Instant in the below illustration

ConvertJavaUtilDateToInstant.java

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

import java.time.Instant;
import java.util.Date;

public class ConvertJavaUtilDateToInstant {

	public static void main(String[] args) {

		// get current Date/Time
		Date date = new Date();
		System.out.println("Current Date/time is :- \n" 
				+ date);


		// convert Date to an Instant
		Instant instant = date.toInstant();
		System.out.print("\nConversion of Date to an Instant is :- \n" 
				+ instant);
	}
}

Output:

Current Date/time is :- 
Sat Aug 20 17:55:08 IST 2022

Conversion of Date to an Instant is :- 
2022-08-20T12:25:08.134Z

Related Articles:

References:

Happy Coding !!
Happy Learning !!

Java 8 – How to convert Instant to java.sql.Timestamp and vice-versa ?
Java 8 – How to convert Instant to number of Milliseconds and vice-versa ?