Java Program to convert java.util.Date to any local date in certain timezone

Java 8Object Oriented ProgrammingProgramming

First, set the Date and ZoneId −

Date date = new Date();
ZoneId zone = ZoneId.systemDefault();

Now convert the java.util.date to localdate −

date.toInstant().atZone(zone).toLocalDate()
date.toInstant().atZone(zone).toLocalTime()
date.toInstant().atZone(zone).getHour()
date.toInstant().atZone(zone).getMinute()
date.toInstant().atZone(zone).getSecond()

Example

import java.time.ZoneId;
import java.util.Date;
public class Demo {
   public static void main(String[] args) {
      Date date = new Date();
      ZoneId zone = ZoneId.systemDefault();
      System.out.println("LocalDate = "+date.toInstant().atZone(zone).toLocalDate());
      System.out.println("LocalTime= "+date.toInstant().atZone(zone).toLocalTime());
      System.out.println("Hour = "+date.toInstant().atZone(zone).getHour());
      System.out.println("Minute = "+date.toInstant().atZone(zone).getMinute());
      System.out.println("Seconds = "+date.toInstant().atZone(zone).getSecond());
   }
}

Output

LocalDate = 2019-04-18
LocalTime= 23:25:09.708
Hour = 23
Minute = 25
Seconds = 9
raja
Published on 26-Apr-2019 10:08:54
Advertisements