Wednesday, April 19, 2017

From LocalDate to LocalDateTime

How to convert LocalDate to LocalDateTime?

Local Date and Local DateTime is introduced in Java 8 under package java.time.

First we need to understand what we have and what we want to get.

From LocalDate we have: Instant + System default time zone.
What we want to have is: Instant + System default time zone + Local Time

LocalDateTime.of() methods gives us so many options to create LocalDateTime. On of the option is as given below

LocalDate localDate = LocalDate.now()

LocalDateTime ldt= LocalDateTime.of(localDate, LocalTime.MIN);

Here LocalTime.Min will give us the Day's start time i.e. 00:00:00
To get LocalDateTime with current time we can use following:

LocalDateTime localDateTimeNow = LocalDateTime.of(localDate, LocalTime.now());

Example:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.ZoneId;
import java.util.Date;

public class LocalDateToLocalDateTime {

 public static void main(String[] args) {

  // Asia/Kuala_Lumpur +8
  ZoneId defaultZoneId = ZoneId.systemDefault();
  System.out.println("System Default TimeZone : " + defaultZoneId);

  Date date = new Date();
  System.out.println("date : " + date);

  // 1. Convert Date -> Instant
  Instant instant = date.toInstant();
  System.out.println("instant : " + instant); // Zone : UTC+0

  // 2. Instant + system default time zone + toLocalDate() = LocalDate
  LocalDate localDate = instant.atZone(defaultZoneId).toLocalDate();
  System.out.println("localDate : " + localDate);

  // 3. Instant + system default time zone + toLocalDateTime() =
  // LocalDateTime
  LocalDateTime localDateTime = instant.atZone(defaultZoneId).toLocalDateTime();
  System.out.println("localDateTime : " + localDateTime);

  LocalDateTime ldt = LocalDateTime.of(localDate, LocalTime.now());
  System.out.println("localDateTime : " + ldt);
 }
}

2 comments:

  1. It’s very rare to be found in such an easy way as you done. Thanks :)

    ReplyDelete
  2. APTRON, a renowned institute for professional IT training, offers comprehensive Java Training in Gurgaon, equipping students and professionals with the skills needed to thrive in the competitive tech industry. With a focus on practical, hands-on learning, APTRON ensures that participants gain a deep understanding of Java programming concepts and tools through immersive training sessions led by industry experts.

    ReplyDelete

Java garbage collection

In this post , we ’ ll take a look at how garbage collection works , why it ’ s important in Java , and how it works in...