Thursday, September 6, 2018

Java8- Learn LocalDateTime Basics with Example

java.time.LocalDateTime

Java8- Learn LocalDateTime Basics with Example

LocalDateTime is introduced in java8 language as part of Date and Time API enhancement. It represents Date and time without timezone information in 2018-09-06T06:12:40 It is immutable object once created, will not be modified It is used to store dates like birthday and holidays with time information. Local Date contains only year, month, Day, hour, minute, second with nano-precision.

Syntax and Signature 

This class implements ChronoLocalDateTime of LocalDate
public final class LocalDateTime
        implements Temporal, TemporalAdjuster, ChronoLocalDateTime<LocalDate>, Serializable 

Examples 

We will see how we can use LocalDateTime with usage examples

How to get Current Date and Time

now() method return the date and time using default system timezone.
LocalDateTime currentDateTime = LocalDateTime.now();
System.out.println(currentDateTime); //2018-09-06T21:52:49.714773400
It has a static of() method which takes java.time.LocalDate and java.time.LocalTime to create LocalDateTime object. Here is an example of a method usage.
LocalDateTime currentDateTime  = LocalDateTime.of(LocalDate.now(), LocalTime.now());
System.out.println(currentDateTime);

Convert String Date to LocalDateTime 

The localdatetime .parse method which accepts string object and DateTimeFormatter instance. The datetimeformatter object created with pattern
String string = "2018-12-12 12:30";
DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");
LocalDateTime localDateTime = LocalDateTime.parse(string, dateTimeFormatter);
System.out.println(localDateTime); //2018-12-12T12:30

How to Convert LocalDateTime to java.util.Date 

The date is legacy Date class and LocalDateTime introduced in java8 version.
LocalDateTime localDateTime =LocalDateTime.now();
Date date = java.sql.Timestamp.valueOf( localDateTime );
System.out.println(date);

Convert LocalDateTime to Instant 

It provides ofInstant() method which takes instant object and zone id- system default zone id LocalDateTime.toInstant() method is used to Convert LocalDateTime to Instant.
Instant instant = Instant.now();
LocalDateTime localDateTime = LocalDateTime.ofInstant(instant, ZoneId.systemDefault());
System.out.println(localDateTime);

How to Create LocalDatetime from Epcoh milliseconds?

System.currentTimeMillis() returns current Epcoh milliseconds. Create Instant using Instant.ofEpochMilli() method, convert Instant to LocalDate time
LocalDateTime localDateTime =
LocalDateTime.ofInstant(Instant.ofEpochMilli(System.currentTimeMillis()), TimeZone
.getDefault().toZoneId());  
System.out.println(localDateTime);

Related article


EmoticonEmoticon