LocalDate and LocalDateTime


Java 8 LocalDate and LocalDateTime objects


Date and LocalDate objects cannot be exactly converted between each other since a Date object represents both a specific day and time, while a LocalDate object does not contain time or timezone information. However, it can be useful to convert between the two if you only care about the actual date information and not the time information.

Creates a LocalDate

// Create a default date
LocalDate lDate = LocalDate.now();
 
// Creates a date from values
lDate = LocalDate.of(2014, 10, 13);
 
// create a date from string
lDate = LocalDate.parse("2014-12-18");
 
// 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(2018, 10, 18, 11, 30);
 
// create a date time from string
lDateTime = LocalDateTime.parse("2018-10-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());

LocalTime


To use just the time part of a Date use LocalTime. You can instantiate a LocalTime object in a couple ways

1. LocalTime time = LocalTime.now();
2. time = LocalTime.MIDNIGHT;
3. time = LocalTime.NOON;
4. time = LocalTime.of(12, 12, 45);

LocalTime also has a built in toString method that displays the format very nicely.

System.out.println(time);

you can also get, add and subtract hours, minutes, seconds, and nanoseconds from the LocalTime object i.e.

time.plusMinutes(1);
time.getMinutes();
time.minusMinutes(1);

You can turn it into a Date object with the following code:

LocalTime lTime = LocalTime.now();
Instant instant = lTime.atDate(LocalDate.of(A_YEAR, A_MONTH, A_DAY)).
      atZone(ZoneId.systemDefault()).toInstant();
Date time = Date.from(instant);

this class works very nicely within a timer class to simulate an alarm clock.

Basic Programs