1. Introduction
Java 8 introduced, through JSR 310, a complete overhaul of the Date/Time API by providing new, more advanced classes for Date processing. LocalDateTime is one such class that we will focus on in this article.
2. What is a LocalDateTime?
LocalDateTime is a class from the java.time
package. The class represents both a date and a time, in terms of date and time fields (year, month, day, hour, minute, second, nanosecond), without any timezone information. The LocalDate and LocalTime classes are covered in separate articles.
The main particularity of LocalDateTime is that it is immutable and thread-safe.
3. Creating a LocalDateTime
There are two main ways of creating a LocalDateTime in Java. The first way is by using the LocalDateTime.now()
methods and the second way is with the LocalDateTime.of()
methods.
3.1. Using LocalDateTime.now()
Methods
You can create a LocalDateTime object with the current date and time in this way:
LocalDateTime now = LocalDateTime.now();//2024-05-05T14:05:46.113681500
This will query the system clock in the default timezone.
Optionally, you can provide a custom Clock to the now()
method:
Clock clock = Clock.systemDefaultZone();
LocalDateTime now = LocalDateTime.now(clock);
It is a best practice to pass a Clock into any method that requires the current instant. This has the advantage of making your code more testable.
Furthermore, if you need to construct a date object for a specific TimeZone, you can pass a ZoneId object to the now()
method:
ZoneId zoneId = ZoneId.of("Europe/Paris");
LocalDateTime now = LocalDateTime.now(zoneId);
3.2. Using LocalDateTime.of()
Methods
You can also create a LocalDateTime object by providing values for the year, month, day, hour, minute, second, and nanosecond fields:
LocalDateTime dateTime = LocalDateTime.of(2024,5,1,13,30,10,5);//2024-05-01T13:30:10.000000005
The second and nanosecond fields are optional. When omitted, they are set to zero.
LocalDateTime dateTime = LocalDateTime.of(2024,5,1,13,30);//2024-05-01T13:30
Instead of sending an integer for the month, you may directly provide a Month Enum object:
LocalDateTime dateTime = LocalDateTime.of(2024,Month.MAY,1,13,30);//2024-05-01T13:30
The LocalDateTime.of()
method can also accept directly a LocalDate
and a LocalTime
objects:
LocalDate date = LocalDate.of(2024,5,1);
LocalTime time = LocalTime.of(13,30);
LocalDateTime dateTime = LocalDateTime.of(date,time);//2024-05-01T13:30
All these factory methods will throw a DateTimeException if the value of any field is out of range, or if the day-of-month is invalid for the month-year.
4. Formatting a LocalDateTime
By default, the LocalDateTime is formatted using the ISO-8601 date format. You can use a different format by passing a DateTimeFormatter object to the format()
method:
LocalDateTime dateTime = LocalDateTime.of(2024,5,1,13,30);// 2024-05-01T13:30
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd/MM/yyyy hh:mm a");
String formattedDateTime = dateTime.format(formatter);// 01/05/2024 01:30 PM
5. Parsing from String to LocalDateTime
Assuming that you have a datetime in ISO-8601 date format and want to build a LocalDateTime out of it, you can use the parse()
method in this way:
String myDateTime = "2024-05-01T13:30";// ISO-8601 date format
LocalDateTime dateTime = LocalDateTime.parse(myDateTime);// 2024-05-01T13:30
Moreover, if the datetime is in a different format, you can pass a custom DateTimeFormatter to the parse()
method:
String myDateTime = "01/05/2024 01:30 PM";//Custom format
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd/MM/yyyy hh:mm a");
LocalDateTime dateTime = LocalDateTime.parse(myDateTime, formatter);// 2024-05-01T13:30
Java will throw a DateTimeParseException if it is not able to parse the String with the given datetime format.
6. Operating on a LocalDateTime
6.1. Comparing two LocalDateTime objects
You can use isAfter()
and isBefore()
methods to compare two LocalDateTime objects:
LocalDateTime firstDateTime = LocalDateTime.of(2024,5,1,13,30);
LocalDateTime secondDateTime = LocalDateTime.of(2024,5,1,13,27);
LocalDateTime thirdDateTime = LocalDateTime.of(2024,5,1,13,33);
LocalDateTime fourthDateTime = LocalDateTime.of(2024,5,1,13,30);
boolean test1 = firstDateTime.isAfter(secondDateTime);//true
boolean test2 = firstDateTime.isBefore(thirdDateTime);//true
boolean test3 = firstDateTime.isEqual(fourthDateTime);//true
Since the LocalDateTime class implements the Comparable<E>
interface, you may also use the compareTo()
method:
LocalDateTime firstDateTime = LocalDateTime.of(2024,5,1,13,30);
LocalDateTime secondDateTime = LocalDateTime.of(2024,5,1,13,27);
LocalDateTime thirdDateTime = LocalDateTime.of(2024,5,1,13,33);
int test1 = firstDateTime.compareTo(secondDateTime);//A positive number
int test2 = firstDateTime.compareTo(thirdDateTime);//A negative number
Lastly, you should know that the LocalDateTime class also overrides the equals()
method and provides a convenient way to check the equality of two dates:
LocalDateTime firstDateTime = LocalDateTime.of(2024,5,1,13,30);
LocalDateTime secondDateTime = LocalDateTime.of(2024,5,1,13,27);
LocalDateTime thirdDateTime = LocalDateTime.of(2024,5,1,13,30);
boolean test1 = firstDateTime.equals(secondDateTime);// false
boolean test2 = firstDateTime.equals(thirdDateTime);// true
6.2. Temporal Arithmetic with LocalDateTime objects
The LocalDateTime class provides plusXXX()
and minusXXX()
methods to increment and decrement the object field values. Since the LocalDateTime is immutable, all these methods return a copy of the original object with the given fields updated.
LocalDateTime dateTime = LocalDateTime.of(2024,5,1,13,30);
LocalDateTime nextYear = dateTime.plusYears(1);//2025-05-01T13:30
LocalDateTime previousYear = dateTime.minusYears(1);//2023-05-01T13:30
LocalDateTime nextMonth = dateTime.plusMonths(1);//2024-06-01T13:30
LocalDateTime previousMonth = dateTime.minusMonths(1);//2024-04-01T13:30
LocalDateTime nextDay = dateTime.plusDays(1);//2024-05-02T13:30
LocalDateTime previousDay = dateTime.minusDays(1);//2024-04-30T13:30
LocalDateTime nextHour = dateTime.plusHours(1);//2024-05-01T14:30
LocalDateTime previousHour = dateTime.minusHours(1);//2024-0-01T12:30
LocalDateTime nextMinute = dateTime.plusMinutes(1);//2024-05-01T13:31
LocalDateTime previousMinute = dateTime.minusMinutes(1);//2024-05-01T13:29
7. Conclusion
In this tutorial, you learned about the LocalDateTime class in Java.
8. References
1) OCP Oracle Certified Professional Java SE 17 by Khalil A. Mughal and Vasily A. Strelnikov
2) Oracle Java Documentation
Pingback: LocalDate Class in Java
Pingback: LocalTime Class in Java
Pingback: Instant Class in Java
Pingback: ZonedDateTime Class in Java