Java 8 LocalDateTime
In this article, we will take a look at LocalDateTime
in java, its meaning and how to create a date with year, month and date in java.
LocalDateTime
is a new class introduced in Java 8 in java.time
package.
It represents a date and time without any time zone information. It combines date information (year, month, and day) from LocalDate and time information (hour, minute, second, and nanosecond) from LocalTime.
LocalDateTime
is an immutable class. This means that once an instance of LocalDateTime
is created, it cannot be modified.
LocalDateTime
is also a final class. This means that you cannot extend and modify its functionality.
Creating LocalDateTime
LocalDateTime
object can be created using it static of()
method, which takes the year, month, day, hour, minute, and second as arguments as shown below
// will print 2023-01-23T12:00 LocalDateTime dateTime = LocalDateTime.of(2023, Month.JANUARY, 23, 12, 0, 0);
now()
returns date-time in yyyy-MM-ddTHH:mm:ss format.
Create LocalDate with values
We can create a LocalDateTime
object with specific year, month, day, hour, minute, and second values using of()
method.
There are multiple overloaded of() methods, which accepts different values for each of these.
Below example creates a LocalDateTime
object for January 23, 2023 at 12:00:00 (noon).
LocalDateTime dateTime = LocalDateTime.of(2022, Month.JANUARY, 1, 12, 0, 0);
All values must be valid. So, using 25 for hour will throw
java.time.DateTimeException: Invalid value for HourOfDay (valid values 0 – 23): 25
Another way of creating its object using values is with its various methods such as withYear()
, withMonth()
etc., as shown below
LocalDateTime dateTime = LocalDateTime.now(); dateTime = dateTime.withYear(2023); dateTime = dateTime.withMonth(Month.JANUARY.getValue()); dateTime = dateTime.withDayOfMonth(23); dateTime = dateTime.withHour(12); dateTime = dateTime.withMinute(0); dateTime = dateTime.withSecond(0);
Create LocalDateTime From string
It is possible to create an object of LocalDateTime
object from a string using its parse()
method, which accepts a string argument. Example,
String dateTimeSt = "2023-01-23 12:00:00"; LocalDateTime dateTime = LocalDateTime.parse(dateTimeStr);
If you want to parse dates of different format, then use overloaded parse()
method, which takes an object of DateTimeFormatter
with custom format
String dateTimeStr = "2023-01-23 12:00:00"; DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); LocalDateTime dateTime = LocalDateTime.parse(dateTimeStr, formatter);
Get Fields from LocalDateTime
If you have a LocalDateTime
object, then you can get fields of this date such as year, month as a number, name of month, date, day of month, day of year etc., using its corresponding get()
methods as shown below
LocalDateTime dateTime = LocalDateTime.now(); int year = dateTime.getYear(); int month = dateTime.getMonthValue(); int day = dateTime.getDayOfMonth(); int hour = dateTime.getHour(); int minute = dateTime.getMinute(); int second = dateTime.getSecond(); System.out.println("Date:" + now); System.out.println("Year: " + now.getYear()); System.out.println("Month name: " + now.getMonth()); System.out.println("Month value: " + now.getMonthValue()); System.out.println("Current Hour: " + now.getHour()); System.out.println("Current Minute: " + now.getMinute()); System.out.println("Day of month: " + now.getDayOfMonth()); System.out.println("Day of year: " + now.getDayOfYear()); System.out.println("Day of week: " + now.getDayOfWeek());
This prints
Date: 2023-01-24T16:04:03.756169600
Year: 2023
Month name: JANUARY
Month value: 1
Current Hour: 16
Current Minute: 4
Day of month: 24
Day of year: 24
Day of week: TUESDAY
You can also retrieve the fields using get()
method, which takes an object of type TemporalField
as shown below.
LocalDateTime dateTime = LocalDateTime.of(2023, Month.JANUARY, 23, 12, 0, 0); int year = dateTime.get(ChronoField.YEAR); int month = dateTime.get(ChronoField.MONTH_OF_YEAR); int day = dateTime.get(ChronoField.DAY_OF_MONTH); int hour = dateTime.get(ChronoField.HOUR_OF_DAY); int minute = dateTime.get(ChronoField.MINUTE_OF_HOUR); int second = dateTime.get(ChronoField.SECOND_OF_MINUTE);
Comparing two
LocalDateTime
objects means determining that the value of date/time contained by which object falls earlier or after the other object.
There are various ways to compare two LocalDateTime
objects.
1. Using compareTo()
This method compares two LocalDateTime
objects and returns an integer value. It returns either of the following values:
< 0 : If the first LocalDateTime
is before the second,
0 : if both objects represent same date/time, and
> 0 : if the first LocalDateTime
is after the second. Example,
LocalDateTime dt1= LocalDateTime.of(2022, Month.JANUARY, 1, 23, 30); LocalDateTime dt2 = LocalDateTime.of(2023, Month.JANUARY, 2, 23, 30); int result = dt1.compareTo(dt2); if(result == 0) { System.out.println(dt1 + " is equal to " + dt2); } else { if(result < 0) { System.out.println(dt1 + " is before " + dt2); } else { System.out.println(dt1 + " is after " + dt2); } }
2. Using isBefore()
isBefore()
method accepts another LocalDateTime
object as argument and returns true
if the LocalDateTime
on which it is called is before(or earlier than) the argument object. Example,
if(dt1.isBefore(dt2)) { System.out.println(dt1 + " is before " + dt2); } else { System.out.println(dt1 + " is after " + dt2); }
3. Using isAfter()
This method is reverse of isBefore() and returns true, if the LocalDateTime
on which it is called is after(or later than) the argument object. Example,
if(dt1.isAfter(dt2)) { System.out.println(dt1 + " is after " + dt2); } else { System.out.println(dt2 + " is not after " + dt2); }
4. Using isEqual()
This method returns a boolean value indicating whether the LocalDateTime
on which it is called is the same(represents same date/time) as the argument object. Example,
if(dt1.isEqual(dt2)) { System.out.println(dt1 + " is equal to " + dt2); } else { System.out.println(dt1 + " is not equal to " + dt2); }
Adding values to LocalDateTime
You can add values to various fields of a LocalDateTime
object using their corresponding plus()
methods as shown below.
Remember that the object returned by plus()
methods will be a different object since LocalDateTime
is immutable.
LocalDateTime now = LocalDateTime.now(); LocalDateTime afterYear = now.plusYears(1); System.out.println("Current date/time" + now); System.out.println("Date/Time after adding 1 year: " + afterYear); LocalDateTime afterDays = now.plusDays(10); System.out.println("Date/Time after adding 10 days: " + afterDays);
This prints
Current date/time2023-01-24T16:45:09.825504500
Date/Time after adding 1 year: 2024-01-24T16:45:09.825504500
Date/Time after adding 10 days: 2023-02-03T16:45:09.825504500
Apart from specific plus()
methods as shown above, there are two other plus()
methods as shown below
1. plus(long amountToAdd, TemporalField field)
This method adds the specified amount to the field provided as TemporalField
in the second argument. Example,
LocalDateTime now = LocalDateTime.now(); LocalDateTime plusDays = currentTime.plus(2, ChronoField.DAY_OF_MONTH); System.out.println("Current time plus 2 days: " + plusDays);
Remember that the object returned will be different from the object on which plus()
is invoked.
2. plus(TemporalAmount amountToAdd)
In this method, we can pass an object of type Period
, which contains the field as well as the amount to be added. Example,
Period period = Period.ofMonths(5); LocalDateTime plusMonths = currentTime.plus(period); System.out.println("Now plus 5 months: " + plusMonths);
plus()
methods, there are minus()
methods as well to subtract values from a LocalDateTime
object.Hope the article was useful.