Sitemap
Ibnu Arseno

Ibnu Arseno

Exploring the intricacies of building modern web applications. Join my journey of learning and sharing.

java Date-Time API conversion

1 min readNov 14, 2021

--

In this article, we will discuss the Java Date-Time data conversion. In the latest Java Date-Time API there are features for converting data from LocalDate to LocalDateTime and vice versa as well as conversion from LocalTime to LocalDateTime and vice versa.

Press enter or click to view image in full size
Photo by Djim Loic on Unsplash

Convert data from LocalDate to LocalDateTime or from LocalDateTime to LocalDate

Sometimes there is a need to convert from LocalDate to LocalDateTime or vice versa. To convert from LocalDateTime to LocalTime, you can use the toLocalDate() method. while to convert from LocalDate to LocalDateTime, you can use the atTime() method.

LocalDateTime localDateTime = LocalDateTime.now();
System.out.println(localDateTime);
LocalDate localDate = localDateTime.toLocalDate();
System.out.println(localDate);

Get Ibnu Arseno’s stories in your inbox

Join Medium for free to get updates from this writer.

LocalDateTime result = localDate.atTime(LocalTime.now());
System.out.println(result);

output:
2021–11–06T21:09:00.653
2021–11–06
2021–11–06T21:14:10.236

Convert data from LocalTime to LocalDateTime or from LocalDateTime to LocalTime

In addition to converting the LocalDate data type, you can also convert from LocalTime to LocalDateTime or vice versa. To convert from LocalDateTime to LocalTime, you can use the toLocalTime() method. while to convert from LocalTime to LocalDateTime can use the atDate() method.

LocalDateTime localDateTime = LocalDateTime.now();
System.out.println(localDateTime);
LocalTime localTime = localDateTime.toLocalTime();
System.out.println(localTime);
LocalDateTime result = localTime.atDate(LocalDate.now());
System.out.println(result);

output:
2021–11–06T21:20:51.379
21:20:51.379
2021–11–06T21:20:51.379

--

--

Ibnu Arseno
Ibnu Arseno

Written by Ibnu Arseno

Exploring the intricacies of building modern web applications. Join my journey of learning and sharing.