Lesson 12 - Date and Time in Java - Creating and formatting
In the previous lesson, ArrayList in Java, we introduced you to the ArrayList class in Java. Today, we're going to explore the other classes which Java provides. You’ll also learn how to work with new date and time in Java 8 and later.
Date and time in Java
Unfortunately, Java’s implementation of date and time has changed multiple times in the past. Many of the early attempts weren't very successful, up to the point where third-party libraries were used instead. Although we’re going to use the implementation introduced in Java 8, let’s go over the legacy (old) classes since you will encounter in other projects, sooner or later:
- Date - The Date class from the java.util package was the first attempt of storing date and time in Java. It's still there for the sake of backward compatibility, however, almost all of its methods are now marked as deprecated. We won't deal with this class at all. If you ever encounter it and want to know exactly how it works, use the official documentation - https://docs.oracle.com/…il/Date.html
- Calendar - The Calendar class is the first replacement of the initial Date class, which brought things like localization or manipulation for inner values. That way, you were able to add time interval and so on. Don't use it for new projects. However, since Java 8 is still relatively new, you'll see this class for sure.
- LocalDate, LocalTime and LocalDateTime - Since Java 8, the LocalDateTime class and its variants are used exclusively for date and/or time. When we compare it to the Calendar class, it's immutable. Simply put, we can use it when working with threads (more on this in later Java courses). It also provides a fluent interface which is sometimes referred to as method chaining. Another good thing about it is that it doesn't mix getting and setting different value parts into a single method. Instead, it provides a variety of individual methods to do so. It surpasses the original Calendar class in both quality and in number of features.
- Joda-Time - The unsuccessful attempts of implementing date and time in Java resulted in a need for a high-quality replacement for built-in classes. The Joda-Time library became quite popular at this point in time. The new Java 8 date API was inspired, in many ways, by this library and even uses the same concepts. One might even say that Joda-Time might be more powerful and of higher quality. However, I suggest that you keep using the standard LocalDateTime class and avoid unnecessary dependencies on third-party components.
A large amount of classes is, whether you like it or not, a Java programmer’s power tools. On the bright side, that's exactly why Java programmers are of the most well-paid among other programming languages. We'll dedicate three articles to date and time. With all of that being said, let's get right to it!
LocalDateTime, LocalDate and LocalTime
As we already know, we'll use the LocalDateTime, LocalDate, and LocalTime classes based on whether we need to store both date and time (e.g. a flight departure), date only (e.g. a birth date), or time only (e.g.: 10:00, nanosecond accuracy).
We’ll start by creating instances of those classes. Create a new project and name it DateAndTime.
Creating from given values
When we create a new instance of one of the classes, we have to call the factory of() method on the class and pass the desired parameters to it. The method has multiple overloads. You can specify seconds, or a month by a number or by an enumerated type (which is probably more readable, more about them later on in the course) as well as several others.
// Date and time LocalDateTime dateTime = LocalDateTime.of(2016, Month.APRIL, 15, 3, 15); System.out.println(dateTime); // Date only LocalDate date = LocalDate.of(2016, Month.APRIL, 15); System.out.println(date); // Time only LocalTime time = LocalTime.of(3, 15, 10); System.out.println(time);
Don't forget to import the classes:
import java.time.LocalDate; import java.time.LocalDateTime; import java.time.LocalTime; import java.time.Month;
Console application 2016-04-15T03:15 2016-04-15 03:15:10
Creating according to the current date and time
As you already know, we'll have to retrieve the current date and time in lots of future applications. To do so, we’ll call the now() factory method right on the corresponding class:
// Current date and time LocalDateTime dateTime = LocalDateTime.now(); System.out.println(dateTime); // Curent date LocalDate date = LocalDate.now(); System.out.println(date); // Current time LocalTime time = LocalTime.now(); System.out.println(time);
The output isn't user-friendly at all, so let's format it! As you may have guessed, we're going to use the format() method to do so. However, this time, we'll call on an instance. The formatting will then be provided by the DateTimeFormatter class. We'll be using the following static methods on it:
- ofLocalizedDateTime() - Formats to a local date and time format. It takes two parameters - the date style and the time style. We can choose anything from the full format to the short format, this applies for all of the methods except for ofPattern().
- ofLocalizedDate() - Formats to the local date format
- ofLocalizedTime() - Formats to the local time format
- ofPattern() - This method makes it so that we can add a custom format using a string containing format symbols. For example, the day, month, year, hours, minutes, and seconds (all numbers) would be specified using the following string "d.M.y H:m:ss". The description of all of the symbols is quite exhausting and can be found in the official Java documentation - https://docs.oracle.com/…rmatter.html
Here’s an example of each one:
LocalDateTime dateTime = LocalDateTime.now(); System.out.println(dateTime.format(DateTimeFormatter.ofLocalizedTime(FormatStyle.MEDIUM))); System.out.println(dateTime.format(DateTimeFormatter.ofLocalizedDate(FormatStyle.FULL))); System.out.println(dateTime.format(DateTimeFormatter.ofLocalizedDateTime(FormatStyle.LONG, FormatStyle.SHORT))); System.out.println(dateTime.format(DateTimeFormatter.ofPattern("M/d/y H:m:ss")));
Don't forget to add imports. I won't remind you this in further examples, in case of errors related to unimported classes, just click on the lightbulb icon in NetBeans and choose to import the class.
import java.time.format.DateTimeFormatter; import java.time.format.FormatStyle;
Here’s the result:
Console application 8:13:04 PM Friday, December 9, 2016 December 9, 2016 8:13 PM 12/9/2016 20:13:04
Notice how we set the style (using the FormatStyle enum), which indicates whether we want a full or a brief output. The following values may also be used:
- FULL - Returns the date as "Friday, December 6, 2016". This one is not suitable for time and throws an exception if it’s used for it.
- LONG - Returns the date as "December 6, 2016". This one is not suitable for time and throws an exception if it’s used for it.
- MEDIUM - Returns the date as "Dec 6, 2016", the time as "3:15:10".
- SHORT - Returns the date as "12/6/2016", the time as "3:15".
There are also some predefined ISO formats set as constants in the DateTimeFormatter class. However, they're not very user friendly, so we won't use them.
Since date and time in Java is a rather long topic, we'll continue discussing it in the next lesson as well. We'll convert between LocalDate, LocalTime, and LocalDateTime as well as modify the inner value and introduce time intervals.
No one has commented yet - be the first!