June 25, 2022

Java Program to Convert Date to LocalDate, LocalDateTime

In this post we’ll see Java programs to convert Date to LocalDate, Date to LocalTime and Date to LocalDateTime.

The java.util.Date represents date and time in coordinated universal time (UTC). In the new Date and Time API available from Java 8 there are the following three classes for representing date and time.

  • LocalDate represents a date without a time-zone.
  • LocalTime represents a time without a time-zone.
  • LocalDateTime represents a date-time without a time-zone.

Converting Date to LocalDate, LocalTime, LocalDateTime

Steps to convert Date to LocalDate, LocalTime or LocalDateTime are as follows.

  1. Since java.util.Date class represents a specific instant in time so first thing is to convert it to java.time.Instant.
  2. Using atZone(ZoneId zone) method of the Instant class you can combine this instant with a time-zone to create a ZonedDateTime.
  3. Once you have a ZonedDateTime instance, using toLocalDate(), toLocalTime(), toLocalDateTime() methods you can get the LocalDate, LocalTime, LocalDateTime respectively.
import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.util.Date;

public class ConvertDate {

  public static void main(String[] args) {
    Date date = new Date();
    System.out.println("Date- " + date);
    //Convert Date to Instant
    Instant instant = date.toInstant();
    //Combine with time-zone
    ZonedDateTime zdt = instant.atZone(ZoneId.systemDefault());
    
    //ZonedDateTime
    System.out.println("ZonedDateTime- " + zdt);
    
    //Get the localdate part
    LocalDate ld = zdt.toLocalDate();
    System.out.println("LocalDate- " + ld);
    
    //Get the LocalTime
    LocalTime lt = date.toInstant().atZone(ZoneId.systemDefault()).toLocalTime();
    System.out.println("LocalTime- " + lt);	
    
    //Get the LocalDateTime
    LocalDateTime ldt = date.toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime();
    System.out.println("LocalDateTime- " + ldt);		
  }
}
Output
Date- Sat Nov 02 19:11:31 IST 2019
ZonedDateTime- 2019-11-02T19:11:31.832+05:30[Asia/Calcutta]
LocalDate- 2019-11-02
LocalTime- 19:11:31.832
LocalDateTime- 2019-11-02T19:11:31.832

That's all for the topic Java Program to Convert Date to LocalDate, LocalDateTime. If something is missing or you have something to share about the topic please write a comment.


You may also like

No comments:

Post a Comment