10 Example of LocalDate, LocalTime, and LocalDateTime in Java 8

It's been almost 5 years since Java SE 8 was released on 17th March 2014 and Java 8 adoption has come a long way. Java programmers around the world have accepted with both ends, many companies have switched their development on Java 8 and several others are migrating to Java 8 platform. At this time, its extremely important for a Java developer to learn and share his Java 8 skill and that just not include lambdas, stream, method reference, functional interface, and other more glamorous stuff, you also need to learn the new Date and time API, which you would find using more regularly in your day to day life.

Java has date API from the JDK 1.1. release but it has several flaws e.g. core class the java.util.Date was neither thread-safe nor immutable and most important it wasn't intuitive. The month starts from 0, the year starts in 1900, who knows about that? Not a good design.

They tried to rectify things with the introduction of Calendar API in JDK 1.4 but that was also plagued with similar errors. Finally, they are third time lucky now with a modern, sophisticated and relatively easy to use date and time API.

The new JDK 8 Date and Time API has many good features e.g. date and time are separate, there are separate classes to represent a time for machine and human and it's both thread-safe and immutable as well. The core classes of JDK 8 date APIs are Instant, LocalDate, LocalTime, LocalDateTime, and ZonedDateTime, so we'll start from there.

  1. Instant - represents a time in the time scale, it's equivalent to java.util.Date because that was also a number of millisecond from the epoch time.
  2. LocalDate - is your general purpose date like 4th July or 17th March 2014, as the name suggests it's local, so timezone is the same as your system's local time zone.
  3. LocalTime - as I said, time and date are now separate. This is your general purpose time e.g. 4 PM, 2 AM or 14.34.32, it's also local
  4. LocalDateTime - is a combination of both date and time e.g. 15th June 2016 11:41 PM. You can extract both LocalDate and LocalTime from this class.
  5. ZonedDateTime - is a date time in a particular timezone e.g. 15th June 2016 11:41 PM PST, it's not local and that's why it has timezone information on it. You can use it denote an absolute time anywhere in the world e.g. Independence day of United States fo America in 2016 would start at NewYork on 4th July 2016 12 AM EDT.

So, now you have basic knowledge of Instant, LocalDate, LocalTime, LocalDateTime, and ZonedDateTime of Java 8, now let's see some example to understand them better.  Btw, if you are new in Java world then I also suggest you go through The Complete Java MasterClass to learn Java better and in a more structured way. It's one of the most up-to-date and comprehensive course to learn Java.




1. How to get current date and time in Java 8

You can use the now() factory method from LocalDate, LocalTime, and LocalDateTime to get the current date, time and DateTime in Java 8. Just remember, they will return the local time from your machine:

// 1st example - current date and time in Java 8
LocalDate currentDate = LocalDate.now();
System.out.println("current date in Java 8: " + currentDate);
 
LocalTime currentTime = LocalTime.now();
System.out.println("current time in Java 8: " + currentTime);
 
LocalDateTime currentDateTime = LocalDateTime.now();
System.out.println("current date time in Java 8: " + currentDateTime);
 
Output
current date in Java 8: 2016-06-15
current time in Java 8: 11:59:38.012
current date time in Java 8: 2016-06-15T11:59:38.012



2. How to get the current day, month and year in Java 8

You can get all date related attribute like the day of the month, current month, year, and day of the week from a LocalDate object. It provides several accessor methods like getDayOfMonth(), getMonth(), getYear() and getDayOfWeek() to extract these information.

Wherever possible Java 8 uses Enum to represent a fixed number of things like Month is an enum, DayOfWeek is an enum but year and day of month returns an integer. Let's see the example now:

int day = currentDate.getDayOfMonth();
Month month = currentDate.getMonth();
int year = currentDate.getYear();
DayOfWeek dayOfWeek = currentDate.getDayOfWeek();
System.out.println("Day of Month in Java 8 : " + day);
System.out.println("Current Month in Java 8 : " + month);
System.out.println("Current Year in Java 8 : " + year);
System.out.println("Current Day of Week in Java 8 : " + dayOfWeek);
 
Output
current date in Java 8: 2016-06-15
current time in Java 8: 12:06:08.909
current date time in Java 8: 2016-06-15T12:06:08.909
Day of Month in Java 8 : 15
Current Month in Java 8 : JUNE
Current Year in Java 8 : 2016
Current Day of Week in Java 8 : WEDNESDAY


3. How to represent a particular date in Java 8

You can use LocalDate to represent an arbitrary date in JDK 8. For example, to represent the upcoming United States of America presidential election, which is scheduled on November 8, 2016, you can use LocalDate as shown in the following example:

LocalDate USAPresidentElection2016 = LocalDate.of(2016, Month.NOVEMBER, 8);
System.out.println("When is USA Presidential election? " + USAPresidentElection2016);
 
Output
When is USA Presidential election? 2016-11-08

It's just a date without any timezone information, hence LocalDate is best suitable. Now, if somebody asks you at what time the presidential election will start, you can either say 7 AM or 7 AM on November 8, 2016, then you can use either LocalTime or LocalDateTime to represent that in Java. You can further see The Complete Java MasterClass to learn more about new Date and Time API in Java.

10 Example of LocalDate, LocalTime, and LocalDateTime in Java 8


4. How to convert java.util.Date to LocalDate, LocalTime, and LocalDateTime 

You can convert legacy date class java.util.Date to new date-time classes e.g. LocalDate, LocalTime and LocalDateTime by using Instant class. The java.time.Instnat is the equivalent class of java.util.Date hence a toInstant() method is added in legacy date class to facilitate the conversion.

Once you get the Instant, you can convert it into LocalDateTime by specifying timezone as default or local timezone by using ZoneId.systemDefault() method.

Once you got the LocalDateTime, you can extract LocalDate and LocalTime by using toLocalDate() and toLocalTime() method as shown below:

Date now = new Date();
Instant instant = now.toInstant();
LocalDateTime dateTime = LocalDateTime.ofInstant(instant, ZoneId.systemDefault());
LocalDate date = dateTime.toLocalDate();
LocalTime time = dateTime.toLocalTime();
System.out.println("legacy date: " + now);
System.out.println("converted LocalDate: " + date);
System.out.println("converted LocalTime: " + time);
System.out.println("converted LocalDateTime: " + dateTime);
Output
legacy date: Wed Jun 15 12:21:08 SGT 2016
converted LocalDate: 2016-06-15
converted LocalTime: 12:21:08.950
converted LocalDateTime: 2016-06-15T12:21:08.950


5. How to convert LocalDate, LocalTime and LocalDateTime to Date

This is the opposite of the previous example. In the last example, we have converted legacy java.util.Date class to new LocalDate class and now we'll convert LocalDatetime to java.util.Date in Java 8. Remember, the equivalent class is Instant so we need first convert LocalDateTime to Instant and then convert that Instant to java.util.Date by using fromInstant() static method, newly added on java.util.date to facilitate the conversion between old and new Date API.

Though converting LocalDateTime to Instant is tricky, as you need to specify ZoneOffset, a better approach is to convert LocalDateTime to ZonedDateTime and then convert ZonedDateTime to Instant as shown in the following example.

LocalDateTime aDateTime = LocalDateTime.now();
ZonedDateTime aZonedDateTime = ZonedDateTime.of(aDateTime, ZoneId.systemDefault());
Instant anInstant = aZonedDateTime.toInstant();
Date aDate = Date.from(anInstant);
System.out.println("new LocalDateTime: " + aDateTime);
System.out.println("old legacy date: " + aDate);
 
Output
new LocalDateTime: 2016-06-15T12:32:02.527
old legacy date: Wed Jun 15 12:32:02 SGT 2016
 

You can see the value of both legacy date and new LocalDate are same.



6. How to check if two LocalDates, LocalTime or LocalDateTime are equal

The new classes from JDK 8 date and time API e.g. LocalDate, LocalTime and LocalDateTime all overrides equals() method for equality check, hence you can directly call equals() to see if two dates are equal or not, or two LocalTime instances are equal or not as shown in the following example

LocalDate first = LocalDate.of(2016, Month.JULY, 10);
LocalDate second = LocalDate.of(2016, Month.JULY, 10);
 
if(first.equals(second)){
System.out.println("both dates are equal");
}
 
Output
both dates are equal


7. How to create a date without a year in Java 8

Some dates are recurring i.e. they come every year and hence we don't specify year when talking about them like Christmas day, Fathers Day, Independence Day, or Thanksgiving Day. We just represent them as by month and date like 25th December, 19th June, 4th July or November 24. You can use the MonthDay class from Java 8 to represent such dates in Java now

MonthDay christmas = MonthDay.of(Month.DECEMBER, 25);
MonthDay independencyDay = MonthDay.of(Month.JULY, 4);
System.out.println("Christmas day: " + christmas);
System.out.println("Independence day of United states of America:" + independencyDay);
 
Output
Christmas day: --12-25
Independence day of United states of America:--07-04

You can format the output as you wish by using DateTimeFormatter class of Java 8, by default toString() display two dashes for a year and then month and day. See Java 8 New Features in Simple Way to learn more about new features of Java 8.

 How to create a date without a year in Java 8


8. How to add days in LocalDate in Java 8

You can add or subtract days from LocalDate using plusDays() and minusDays() method, for example, if you have today's date you can get tomorrow's date by adding just one day and the day after tomorrow's date by adding 2 dates. Similarly, you can find yesterday's date by subtracting 1-day using minusDays() method as shown below:

LocalDate tommorrow = currentDate.plusDays(1);
LocalDate dayAfterTommorrow = currentDate.plusDays(2);
LocalDate yesterday = currentDate.minusDays(1); 
System.out.println("tommorrow (adding 1 day) : " + tommorrow);
System.out.println("day after tommorrow : " + dayAfterTommorrow);
System.out.println("yesterday : " + yesterday);
 
Output
tommorrow (adding 1 day) : 2016-06-16
day after tommorrow : 2016-06-17
yesterday : 2016-06-14 

You can further add month and year to a LocalDate by following the same pattern e.g by using plusMonth() and minusMonth() method to add a month and using plusYear() and minusYear() to add year into LocalDate.



9. How to add time in LocalTime in Java 8 

Similar to the previous example, you can also add or subtract an hour, minute and seconds from a LocalTime instance by using plusHours(), plusMinutes(), and minusHours(), minusMinutes() as shown in the following example:

LocalTime nextHour = currentTime.plusHours(1);
LocalTime lastHour = currentTime.minusHours(1);
LocalTime after30Minutes = currentTime.plusMinutes(30);
System.out.println("adding 1 hour on LocalTime: " + nextHour);
System.out.println("subtracting 1 hour from LocalTime: " + lastHour);
System.out.println("adding 30 minutes : " + after30Minutes);
 
Output
adding 1 hour on LocalTime: 13:55:52.801
subtracting 1 hour from LocalTime: 11:55:52.801
adding 30 minutes : 13:25:52.801

You can further explore LocalTime class for several others time manipulation method e.g. plusSeconds() to add seconds and plusNanons() to add nanosecond.

Though, you must keep in mind that these methods return a new instance of LocalTime class because LocalTime is Immutable, hence you must store them into a new reference. Following code highlight a common mistake many Java developer made while manipulating LocalDate and LocalTime in Java:

LocalTime justNow = LocalTime.now();
System.out.println("just now: " + justNow);
currentTime.plusHours(1);
System.out.println("next hour: " + justNow);
currentTime.minusHours(1);
System.out.println("last hour: " + justNow);
 
Output
just now: 13:01:51.160
next hour: 13:01:51.160
last hour: 13:01:51.160

You can see even after calling plusHours() or minusHours() there is no change in LocalTime because it's immutable and we are not storing result returned by those methods which are different objects. Same is true when you add a day, month or year in LocalDate, so beware of that.



10. How to convert LocalDateTime to ZonedDateTime in Java 8

Since LocalDateTime is local or has default timezone, you need to provide a timezone when you convert a LocalDateTime to ZonedDateTime. For example, you can check what is the current time in London by converting your local date-time instance to zoned date time and using ZoneId for "Europe/London" as shown in the following example:

LocalDateTime myDateTime = LocalDateTime.now();
ZonedDateTime ukDateTime = ZonedDateTime.of(aDateTime, ZoneId.of("Europe/London"));
System.out.println("local time: " + myDateTime);
System.out.println("london time: " + ukDateTime);
Output
local time: 2016-06-15T13:06:37.423
london time: 2016-06-15T13:06:37.409+01:00[Europe/London]

This is a nice way to check the current time around the world, all you need to know is the timezone String like "Europe/London". See Java Fundamentals Part 1 and 2 to learn more about TimeZone and how to deal with them in Java.

How to convert LocalDateTime to ZonedDateTime in Java 8



11. How to convert ZonedDateTime to LocalDateTime in Java 8

We have seen this before while converting LocalDateTime to java.util.Date previously. It's very easy to convert ZonedDateTime to LocalDateTime, just remove the timezone information by using toLocalDateTime() method as shown in the following example:

ZonedDateTime USATime = ZonedDateTime.of(aDateTime, ZoneId.of("America/New_York"));
LocalDateTime local = USATime.toLocalDateTime();
System.out.println("NewYork time: " + USATime);
System.out.println("local time: " + local);
 
Output
NewYork time: 2016-06-15T13:14:30.538-04:00[America/New_York]
local time: 2016-06-15T13:14:30.538




Java Program - LocalDate, LocalTime and LocalDateTime Example

Here is the complete Java program to run all the examples we have seen so far related to new Java 8 date and time classes:
package test;

import java.time.DayOfWeek;
import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.Month;
import java.time.MonthDay;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.util.Date;
 
/**
 * Java Program to demonstrate how to use LocalDate, LocalTime, and
 * LocalDateTime in Java 8.
 */
public class JavaApplication1 {
 
    public static void main(String[] args) {
 
        // 1st example - current date and time in Java 8
        LocalDate currentDate = LocalDate.now();
        System.out.println("current date in Java 8: " + currentDate);
 
        LocalTime currentTime = LocalTime.now();
        System.out.println("current time in Java 8: " + currentTime);
 
        LocalDateTime currentDateTime = LocalDateTime.now();
        System.out.println("current date time in Java 8: " + currentDateTime);
 
        // 2nd example - current day, month, and year in Java 8
        int day = currentDate.getDayOfMonth();
        Month month = currentDate.getMonth();
        int year = currentDate.getYear();
        DayOfWeek dayOfWeek = currentDate.getDayOfWeek();
        System.out.println("Day of Month in Java 8 : " + day);
        System.out.println("Current Month in Java 8 : " + month);
        System.out.println("Current Year in Java 8 : " + year);
        System.out.println("Current Day of Week in Java 8 : " + dayOfWeek);
 
        // 3rd example - representing an arbitrary date in Java 8
        LocalDate USAPresidentElection2016 = LocalDate.of(2016, Month.NOVEMBER, 8);
        System.out.println("When is USA Presidential election? " 
                                + USAPresidentElection2016);       
 
 
        // 4th Exmaple - converting between legacy date and new LocalDate
        Date now = new Date();
        Instant instant = now.toInstant();
        LocalDateTime dateTime = LocalDateTime.ofInstant(instant,
                                                  ZoneId.systemDefault());
        LocalDate date = dateTime.toLocalDate();
        LocalTime time = dateTime.toLocalTime();
        System.out.println("legacy date: " + now);
        System.out.println("converted LocalDate: " + date);
        System.out.println("converted LocalTime: " + time);
        System.out.println("converted LocalDateTime: " + dateTime);
 
        // 5th Example - converting new classes to legacy class in Java 8
        LocalDateTime aDateTime = LocalDateTime.now();
        ZonedDateTime aZonedDateTime = ZonedDateTime.of(aDateTime,
                                                    ZoneId.systemDefault());
        Instant anInstant = aZonedDateTime.toInstant();
        Date aDate = Date.from(anInstant);
        System.out.println("new LocalDateTime: " + aDateTime);
        System.out.println("old legacy date: " + aDate);
 
        // 6th example - checking if two dates are equal
        LocalDate first = LocalDate.of(2016, Month.JULY, 10);
        LocalDate second = LocalDate.of(2016, Month.JULY, 10);
 
        if (first.equals(second)) {
            System.out.println("both dates are equal");
        }
 
        // 7th example - creating date without year
        MonthDay christmas = MonthDay.of(Month.DECEMBER, 25);
        MonthDay independencyDay = MonthDay.of(Month.JULY, 4);
        System.out.println("Christmas day: " + christmas);
        System.out.println("Independence day of United states of America:" 
                                                + independencyDay);
 
        // 8th example - adding days on LocalDate
        LocalDate tommorrow = currentDate.plusDays(1);
        LocalDate dayAfterTommorrow = currentDate.plusDays(2);
        LocalDate yesterday = currentDate.minusDays(1);
        System.out.println("tommorrow (adding 1 day) : " + tommorrow);
        System.out.println("day after tommorrow : " + dayAfterTommorrow);
        System.out.println("yesterday : " + yesterday);
 
        // 9th Example - adding time on LocalTime
        LocalTime nextHour = currentTime.plusHours(1);
        LocalTime lastHour = currentTime.minusHours(1);
        LocalTime after30Minutes = currentTime.plusMinutes(30);
        System.out.println("adding 1 hour on LocalTime: " + nextHour);
        System.out.println("subtracting 1 hour from LocalTime: " + lastHour);
        System.out.println("adding 30 minutes : " + after30Minutes);
 
        // 10th Example - converting LocalDatetime to ZonedDateTime
        LocalDateTime myDateTime = LocalDateTime.now();
        ZonedDateTime ukDateTime = ZonedDateTime.of(aDateTime, 
                                             ZoneId.of("Europe/London"));
        System.out.println("local time: " + myDateTime);
        System.out.println("london time: " + ukDateTime);
 
        // 11th bonus exmaple - ZonedDateTime to LocalDateTime
        ZonedDateTime USATime = ZonedDateTime.of(aDateTime, 
                                             ZoneId.of("America/New_York"));
        LocalDateTime local = USATime.toLocalDateTime();
        System.out.println("NewYork time: " + USATime);
        System.out.println("local time: " + local);
    }
 
}
 
Output
run:
current date in Java 8: 2019-05-11
current time in Java 8: 20:52:23.173
current date time in Java 8: 2019-05-11T20:52:23.173
Day of Month in Java 8 : 11
Current Month in Java 8 : MAY
Current Year in Java 8 : 2019
Current Day of Week in Java 8 : SATURDAY
When is USA Presidential election? 2016-11-08
legacy date: Sat May 11 20:52:23 GMT+08:00 2019
converted LocalDate: 2019-05-11
converted LocalTime: 20:52:23.302
converted LocalDateTime: 2019-05-11T20:52:23.302
new LocalDateTime: 2019-05-11T20:52:23.318
old legacy date: Sat May 11 20:52:23 GMT+08:00 2019
both dates are equal
Christmas day: --12-25
Independence day of United states of America:--07-04
tommorrow (adding 1 day) : 2019-05-12
day after tommorrow : 2019-05-13
yesterday : 2019-05-10
adding 1 hour on LocalTime: 21:52:23.173
subtracting 1 hour from LocalTime: 19:52:23.173
adding 30 minutes : 21:22:23.173
local time: 2019-05-11T20:52:23.354
london time: 2019-05-11T20:52:23.318+01:00[Europe/London]
NewYork time: 2019-05-11T20:52:23.318-04:00[America/New_York]
local time: 2019-05-11T20:52:23.318
BUILD SUCCESSFUL (total time: 0 seconds)
 

That's all about 10 examples of LocalDate, LocalTime, and LocalDateTime in Java 8. The good thing about the new date and time API are that they are very easy to remember, by name you know that they are local i.e. you don't need timezone information there, but if you have to represent a time in the UK, you need a ZonedDateTime to include timezone in your date.

We have seen examples of creating LocalDate, LocalTime, manipulating them by adding day and hours, converting LocalDate to java.util.Date and vice-versa and also converting ZonedDateTime to LocalDateTime and vice-versa.

If you have any doubt or problem using Java 8 date time class, please let us know and I'll try to help you out.

Further Learning
The Complete Java MasterClass
Java 8 New Features in Simple Way
Java Fundamentals Part 1 and 2


Other Java 8 Date Time Tutorials you may like

  • 5 books to learn Java 8 and Functional Programming (books)
  • How to convert java.util.Date to java.time.LocalDateTime in Java 8? (tutorial)
  • How to convert String to LocalDateTime in Java 8? (tutorial)
  • How to compare two Dates in Java 8? (example)
  • How to convert Timestamp to Date in Java? (example)
  • How to convert old Date to new LocalDate in Java 8? (example)
  • 10 Examples to format and parse Date in Java 8? (tutorial)
  • How to parse String to LocalDateTime in Java 8? (tutorial)
  • How to calculate the difference between two dates in Java? (example)
  • 10 Java Date, Time, and Calendar based Questions from Interviews (questions)
  • How to change the date format of String in Java 8? (tutorial)
  • 20 Examples to learn new Date and Time API in Java 8 (example)
  • 5 Free Courses to learn Java 8 and 9 (courses)
Thanks for reading this article so far, if you like this Java Date and Time tutorial then please share with your friends and colleagues. If you have any questions or feedback please drop a note.

P.S.: If you just want to learn more about new features in Java 8 then please see the course What's New in Java 8. It explains all the important features of Java 8 like lambda expressions, streams, functional interfaces, Optional, new Date Time API and other miscellaneous changes

No comments:

Post a Comment