Convert LocalDateTime to Instant in Java [2 ways]

In this post, I will be sharing how to convert LocalDateTime to Instant in Java. There are two ways to achieve our goal of converting LocalDateTime to Instant in Java:

1. Using LocalDateTime class toInstant() method [Recommended]

2. Using LocalDateTime class toEpochSecond() method

Convert LocalDateTime to Instant in Java

1. Using LocalDateTime class toInstant() method

We can easily convert LocalDateTime to Instant in Java using LocalDateTime.toInstant() method passing ZoneOffset as the input argument as shown below in the example:

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

public class LocalDateTimeToInstant {
    public static void main(String args[]) {
        // Get LocalDateTime object
        LocalDateTime localDateTime = LocalDateTime.now();
        System.out.println("Current LocalDateTime is: "+ localDateTime);
        
        // Convert LocalDateTime to Instant
        Instant instant = localDateTime.toInstant(ZoneOffset.UTC);
        System.out.println("Instant is: "+ instant);
    }
}


Output:
Current LocalDateTime is: 2024-02-01T12:59:06.438734808
Instant is: 2024-02-01T12:59:06.438734808Z


2. Using LocalDateTime class toEpochSecond() method

We can easily convert LocalDateTime to Instant in Java using LocalDateTime.toEpochSecond() and Instant.ofEpochSecond() methods passing ZoneOffset as input argument as shown below in the example:

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

public class LocalDateTimeToInstant2 
{
    public static void main(String args[]) 
    {
      // Get LocalDateTime object
      LocalDateTime localDateTime = LocalDateTime.now();
      System.out.println("Current LocalDateTime is: "+ localDateTime);
      
      // Converting LocalDateTime to Instant
      long timeInSeconds = localDateTime.toEpochSecond(ZoneOffset.UTC);
      Instant instant = Instant.ofEpochSecond(timeInSeconds);
      System.out.println("Instant is: "+ instant);
    }
}


Output:
Current LocalDateTime is: 2024-02-01T14:23:37.175988588
Instant is: 2024-02-01T14:23:37Z


That's all for today. Please mention in the comments if you have any questions related to how to convert LocalDateTime to Instant in Java with examples.

About The Author

Subham Mittal has worked in Oracle for 3 years.
Enjoyed this post? Never miss out on future posts by subscribing JavaHungry