Java 8 LocalDate and LocalDateTime objects

suggest change

java.util.Date and LocalDate cannot be converted without choosing a time zone. A Date is an instant, while a LocalDate has neither a time of day nor a zone. LocalDateTime also has no zone, so converting it to or from a Date needs a ZoneId as well. The conversion is still useful when only the civil date, or the local date and time, matters. LocalDate.of and LocalDateTime.of number months from 1, not from 0.

Creates a LocalDate

// Create a default date
LocalDate lDate = LocalDate.now();

// Creates a date from values
lDate = LocalDate.of(2017, 12, 15);
    
// create a date from string
lDate = LocalDate.parse("2017-12-15");

// creates a date from zone
LocalDate.now(ZoneId.systemDefault());

Creates a LocalDateTime

// Create a default date time
LocalDateTime lDateTime = LocalDateTime.now();

// Creates a date time from values
lDateTime = LocalDateTime.of(2017, 12, 15, 11, 30);

// create a date time from string
lDateTime = LocalDateTime.parse("2017-12-05T11:30:30");

// create a date time from zone 
LocalDateTime.now(ZoneId.systemDefault());

LocalDate to Date and vice-versa

Date date = Date.from(Instant.now());
ZoneId defaultZoneId = ZoneId.systemDefault();

// Date to LocalDate
LocalDate localDate = date.toInstant().atZone(defaultZoneId).toLocalDate();

// LocalDate to Date
Date.from(localDate.atStartOfDay(defaultZoneId).toInstant());

LocalDateTime to Date and vice-versa

Date date = Date.from(Instant.now());
ZoneId defaultZoneId = ZoneId.systemDefault();

// Date to LocalDateTime
LocalDateTime localDateTime =  date.toInstant().atZone(defaultZoneId).toLocalDateTime();

// LocalDateTime to Date
Date out = Date.from(localDateTime.atZone(defaultZoneId).toInstant());

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents