Java Program to convert Instant to LocalDateTime

Java 8Object Oriented ProgrammingProgramming

Let’s say you need to convert Instant to LocalDateTime with IST with timezone:

Create an Instant:

Instant instant = new Date().toInstant();

Now, convert Instant to LocalDateTime:

LocalDateTime date = LocalDateTime.ofInstant(instant, ZoneId.of(ZoneId.SHORT_IDS.get("IST")));

Example

import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;
public class Demo {
   public static void main(String[] args) {
      Instant instant = new Date().toInstant();
      LocalDateTime date = LocalDateTime.ofInstant(instant, ZoneId.of(ZoneId.SHORT_IDS.get("IST")));
      System.out.println("Date (IST) = " + date);
      date = LocalDateTime.ofInstant(instant, ZoneId.of(ZoneId.SHORT_IDS.get("PST")));
      System.out.println("Date (PST) = " + date);
      date = LocalDateTime.ofInstant(instant, ZoneId.of(ZoneId.SHORT_IDS.get("EST")));
      System.out.println("Date (EST) = " + date);
   }
}

Output

Date (IST) = 2019-04-18T13:32:26.923
Date (PST) = 2019-04-18T01:02:26.923
Date (EST) = 2019-04-18T03:02:26.923
raja
Published on 24-Apr-2019 16:26:25
Advertisements