Java 8 – How to convert Instant to number of Milliseconds and vice-versa ?

In this article, we will learn how to convert Instant to number of Milliseconds and vice-versa using toEpochMilli() and ofEpochMilli() methods of Instant respectively provided in Java 1.8 version

Conversion of Instant to Millisecond & vice-versa :

There are 2 methods available in an Instant for conversion of Instant to Millisecond and vice-versa,

  • toEpochMilli() – converts invoking instant to the number of milliseconds from the epoch of 1970-01-01T00:00:00Z
  • ofEpochMilli(epochMilli) – gets an instance of Instant using milliseconds from the epoch of 1970-01-01T00:00:00Z

1. Convert Instant to Milliseconds :

  • toEpochMilli() – Converts an Instant to number of Milliseconds from 1970-01-01T00:00:00Z in long type

ConvertInstantToMilliSeconds.java

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

import java.time.Instant;

public class ConvertInstantToMilliSeconds {

	public static void main(String[] args) {

		// 1. get current Date/time or Instant at UTC
		Instant instant = Instant.now();
		System.out.println("Current Instant at UTC/GMT is :- \n" 
				+ instant);


		// 2. get Milliseconds from an Instant
		long milliseconds = instant.toEpochMilli();
		System.out.print("\nInstant to number of Milliseconds in long type :- \n"
				+ milliseconds);
	}
}

Output:

Current Instant at UTC/GMT is :- 
2022-08-19T17:59:12.020844500Z

Instant to number of Milliseconds in long type :- 
1660931952020

2. Convert Seconds to Instant :

  • ofEpochMilli(long) – This method obtains an instance of Instant from a Milliseconds value provided as argument in long type

ConvertMilliSecondsToInstant.java

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

import java.time.Instant;

public class ConvertMilliSecondsToInstant {

	public static void main(String[] args) {

		// 1. milliseconds in long format
		long milliseconds = 1660931952020L;
		System.out.println("Number of Milliseconds in long type :- \n" 
				+ milliseconds);


		// 2. convert milliseconds to an Instant
		Instant instant = Instant.ofEpochMilli(milliseconds);
		System.out.print("\nMilliseconds to an Instant is :- \n" 
				+ instant);
	}
}

Output:

Number of Milliseconds in long type :- 
1660931952020

Milliseconds to an Instant is :- 
2022-08-19T17:59:12.020Z

Related Articles:

References:

Happy Coding !!
Happy Learning !!

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