Java 8 – How to convert LocalDateTime to an Instant ?

In this article, we will learn how to convert LocalDateTime to an Instant using toInstant(ZoneOffset) method of LocalDateTime/ChronoLocalDateTime provided in Java 1.8 version

For Instant to LocalDateTime conversion, read Java 8 – How to convert Instant to LocalDateTime ?

Convert LocalDateTime to an Instant :

  • LocalDateTime has a method toInstant() which takes ZoneOffset as an argument and returns Instant
    • toInstant() – Converts invoking LocalDateTime to an Instant
  • Using this method, it is very easy to convert LocalDateTime to an Instant by adding zone-offset information
  • After conversion, Instant will represent instantaneous/current moment at GMT/UTC
  • Lets see an example for conversion of LocalDateTime to an Instant in the below illustration

ConvertLocalDateTimeToInstant.java

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

import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneOffset;

public class ConvertLocalDateTimeToInstant {

	public static void main(String[] args) {

		// 1. get current System Date/time
		LocalDateTime localDateTime = LocalDateTime.now();
		System.out.println("Current System Date/time is :- \n" + localDateTime);


		// 2. get system default zone offset
		ZoneOffset zoneOffset = ZoneOffset.of("+05:30");
		System.out.println("\nZone Offset is :- \n" + zoneOffset);


		// 3. convert LocalDateTime to an Instant using toInstant(zoneOffset)
		Instant instant = localDateTime.toInstant(zoneOffset);
		System.out.print("\nConversion of LocalDateTime to Instant is :- \n"
				+ instant);
	}
}

Output:

Current System Date/time is :- 
2022-08-09T12:41:18.150482100

Zone Offset is :- 
+05:30

Conversion of LocalDateTime to Instant is :- 
2022-08-09T07:11:18.150482100Z

Related Articles:

References:

Happy Coding !!
Happy Learning !!

Java 8 – How to extract LocalDate and LocalTime from LocalDateTime ?
Java 8 – How to convert LocalDateTime to an OffsetDateTime ?