Java LocalDateTime Tutorial with Examples
LocalDateTime class represent a date-time without a time-zone in the ISO-8601 calendar system, such as 2016-05-16T10:15:30, often viewed as year-month-day-hour-minute-second. Time is represented to nanosecond precision.
We can simply say that LocalDateTime class is a combination of the LocalDate and LocalTime class. This class is immutable and thread-safe.
Creating a LocalDateTime
We can create a LocalDateTime in several ways:
- static LocalDateTime now(): Obtains the current date-time from the system clock in the default time-zone.
- static LocalDateTime now(Clock clock): Obtains the current date-time from the specified clock.
- static LocalDateTime now(ZoneId zone): Obtains the current date-time from the system clock in the specified time-zone.
- static LocalDateTime of(int year, int month, int dayOfMonth, int hour, int minute): Obtains an instance of LocalDateTime from year, month, day, hour and minute, setting the second and nanosecond to zero.
- static LocalDateTime of(int year, int month, int dayOfMonth, int hour, int minute, int second): Obtains an instance of LocalDateTime from year, month, day, hour, minute and second, setting the nanosecond to zero.
- static LocalDateTime of(int year, int month, int dayOfMonth, int hour, int minute, int second, int nanoOfSecond): Obtains an instance of LocalDateTime from year, month, day, hour, minute, second and nanosecond.
- static LocalDateTime of(int year, Month month, int dayOfMonth, int hour, int minute): Obtains an instance of LocalDateTime from year, month, day, hour and minute, setting the second and nanosecond to zero.
- static LocalDateTime of(int year, Month month, int dayOfMonth, int hour, int minute, int second): Obtains an instance of LocalDateTime from year, month, day, hour, minute and second, setting the nanosecond to zero.
- static LocalDateTime of(int year, Month month, int dayOfMonth, int hour, int minute, int second, int nanoOfSecond): Obtains an instance of LocalDateTime from year, month, day, hour, minute, second and nanosecond.
- static LocalDateTime of(LocalDate date, LocalTime time): Obtains an instance of LocalDateTime from a date and time.
- static LocalDateTime ofEpochSecond(long epochSecond, int nanoOfSecond,ZoneOffset offset): Obtains an instance of LocalDateTime using seconds from the epoch of 1970-01-01T00:00:00Z.
- static LocalDateTime ofInstant(Instant instant, ZoneId zone): Obtains an instance of LocalDateTime from an Instant and zone ID.
- static LocalDateTime parse(CharSequence text): Obtains an instance of LocalDateTime from a text string such as 1997-05-07T10:15:30.
- static LocalDateTime parse(CharSequence text, DateTimeFormatter formatter): Obtains an instance of LocalDateTime from a text string using a specific formatter.
import java.time.Clock;
import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.Month;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
public class LocalDateTimeInitExample {
public static void main(String[] args) {
LocalDateTime localDT1 = LocalDateTime.now();
System.out.println("LocalDateTime1 : " + localDT1);
LocalDateTime localDT2 = LocalDateTime.now(Clock.systemUTC());
System.out.println("LocalDateTime2 : " + localDT2);
LocalDateTime localDT3 = LocalDateTime.now(ZoneId.systemDefault());
System.out.println("LocalDateTime3 : " + localDT3);
LocalDateTime localDT4 = LocalDateTime.of(1980, 4, 9, 20, 15);
System.out.println("LocalDateTime4 : " + localDT4);
LocalDateTime localDT5 = LocalDateTime.of(1980, Month.APRIL, 9, 20, 15);
System.out.println("LocalDateTime5 : " + localDT5);
LocalDateTime localDT6 = LocalDateTime.of(1979, 12, 9, 18, 5, 50);
System.out.println("LocalDateTime6 : " + localDT6);
LocalDateTime localDT7 = LocalDateTime.of(1979, Month.DECEMBER, 9, 18, 5, 50);
System.out.println("LocalDateTime7 : " + localDT7);
LocalDateTime localDT8 = LocalDateTime.of(1983, 7, 12, 20, 15, 50, 345678900);
System.out.println("LocalDateTime8 : " + localDT8);
LocalDateTime localDT9 = LocalDateTime.of(1983, Month.JULY, 12, 20, 15, 50, 345678900);
System.out.println("LocalDateTime9 : " + localDT9);
LocalDateTime localDT10 = LocalDateTime.of(LocalDate.now(), LocalTime.of(15, 50));
System.out.println("LocalDateTime10: " + localDT10);
LocalDateTime localDT11 = LocalDateTime.ofEpochSecond(1555552018, 456789500, ZoneOffset.UTC);
System.out.println("LocalDateTime11: " + localDT11);
LocalDateTime localDT12 = LocalDateTime.ofInstant(Instant.ofEpochMilli(324142255123L), ZoneId.systemDefault());
System.out.println("LocalDateTime12: " + localDT12);
LocalDateTime localDT13 = LocalDateTime.parse("1945-08-17T10:20:45");
System.out.println("LocalDateTime13: " + localDT13);
LocalDateTime localDT14 = LocalDateTime.parse("20190824155025", DateTimeFormatter.ofPattern("yyyyMMddHHmmss"));
System.out.println("LocalDateTime14: " + localDT14);
}
}
LocalDateTime1 : 2019-08-24T16:01:45.629 LocalDateTime2 : 2019-08-24T08:01:45.630 LocalDateTime3 : 2019-08-24T16:01:45.630 LocalDateTime4 : 1980-04-09T20:15 LocalDateTime5 : 1980-04-09T20:15 LocalDateTime6 : 1979-12-09T18:05:50 LocalDateTime7 : 1979-12-09T18:05:50 LocalDateTime8 : 1983-07-12T20:15:50.345678900 LocalDateTime9 : 1983-07-12T20:15:50.345678900 LocalDateTime10: 2019-08-24T15:50 LocalDateTime11: 2019-04-18T01:46:58.456789500 LocalDateTime12: 1980-04-09T23:00:55.123 LocalDateTime13: 1945-08-17T10:20:45 LocalDateTime14: 2019-08-24T15:50:25
Getting Information from a LocalDateTime
Following methods can be used to access Date and/or Time information from a LocalDateTime:
- int get(TemporalField field): Gets the value of the specified field from this date-time as an int.
- Chronology getChronology(): Gets the chronology of this date-time.
- int getDayOfMonth(): Gets the day-of-month field.
- DayOfWeek getDayOfWeek(): Gets the day-of-week field, which is an enum DayOfWeek.
- int getDayOfYear(): Gets the day-of-year field.
- int getHour(): Gets the hour-of-day field.
- long getLong(TemporalField field): Gets the value of the specified field from this date-time as a long.
- int getMinute(): Gets the minute-of-hour field.
- Month getMonth(): Gets the month-of-year field using the Month enum.
- int getMonthValue(): Gets the month-of-year field from 1 to 12.
- int getNano(): Gets the nano-of-second field.
- int getSecond(): Gets the second-of-minute field.
- int getYear(): Gets the year field.
- long toEpochSecond(ZoneOffset offset): Converts this date-time to the number of seconds from the epoch of 1970-01-01T00:00:00Z.
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.temporal.ChronoField;
public class LocalDateTimeInfoExample {
public static void main(String[] args) {
LocalDateTime localDT = LocalDateTime.now();
System.out.println("LocalDateTime : " + localDT);
System.out.println("DayOfMonth : " + localDT.getDayOfMonth());
System.out.println("MonthValue : " + localDT.getMonthValue());
System.out.println("Year : " + localDT.getYear());
System.out.println("Hour : " + localDT.getHour());
System.out.println("Minute : " + localDT.getMinute());
System.out.println("Second : " + localDT.getSecond());
System.out.println("Nano : " + localDT.getNano());
System.out.println("DayOfWeek : " + localDT.getDayOfWeek());
System.out.println("Month : " + localDT.getMonth());
System.out.println("DayOfYear : " + localDT.getDayOfYear());
System.out.println("DAY_OF_MONTH : " + localDT.get(ChronoField.DAY_OF_MONTH));
System.out.println("MONTH_OF_YEAR : " + localDT.get(ChronoField.MONTH_OF_YEAR));
System.out.println("YEAR : " + localDT.get(ChronoField.YEAR));
System.out.println("HOUR_OF_DAY : " + localDT.get(ChronoField.HOUR_OF_DAY));
System.out.println("MINUTE_OF_HOUR : " + localDT.get(ChronoField.MINUTE_OF_HOUR));
System.out.println("SECOND_OF_MINUTE: " + localDT.get(ChronoField.SECOND_OF_MINUTE));
System.out.println("MINUTE_OF_DAY : " + localDT.getLong(ChronoField.MINUTE_OF_DAY));
System.out.println("SECOND_OF_DAY : " + localDT.getLong(ChronoField.SECOND_OF_DAY));
System.out.println("Chronology : " + localDT.getChronology());
System.out.println("toEpochSecond() : " + localDT.toEpochSecond(ZoneOffset.UTC));
}
}
LocalDateTime : 2019-08-25T20:22:59.564 DayOfMonth : 25 MonthValue : 8 Year : 2019 Hour : 20 Minute : 22 Second : 59 Nano : 564000000 DayOfWeek : SUNDAY Month : AUGUST DayOfYear : 237 DAY_OF_MONTH : 25 MONTH_OF_YEAR : 8 YEAR : 2019 HOUR_OF_DAY : 20 MINUTE_OF_HOUR : 22 SECOND_OF_MINUTE: 59 MINUTE_OF_DAY : 1222 SECOND_OF_DAY : 73379 Chronology : ISO toEpochSecond() : 1566764579
Add/Subtract Operations on LocalDateTime
Following methods used for add/subtract operation in a LocalDateTime:
- LocalDateTime minus(long amountToSubtract, TemporalUnit unit): Returns a copy of this date-time with the specified amount subtracted.
- LocalDateTime minus(TemporalAmount amountToSubtract): Returns a copy of this date-time with the specified amount subtracted.
- LocalDateTime minusDays(long days): Returns a copy of this LocalDateTime with the specified number of days subtracted.
- LocalDateTime minusHours(long hours): Returns a copy of this LocalDateTime with the specified number of hours subtracted.
- LocalDateTime minusMinutes(long minutes): Returns a copy of this LocalDateTime with the specified number of minutes subtracted.
- LocalDateTime minusMonths(long months): Returns a copy of this LocalDateTime with the specified number of months subtracted.
- LocalDateTime minusNanos(long nanos): Returns a copy of this LocalDateTime with the specified number of nanoseconds subtracted.
- LocalDateTime minusSeconds(long seconds): Returns a copy of this LocalDateTime with the specified number of seconds subtracted.
- LocalDateTime minusWeeks(long weeks): Returns a copy of this LocalDateTime with the specified number of weeks subtracted.
- LocalDateTime minusYears(long years): Returns a copy of this LocalDateTime with the specified number of years subtracted.
- LocalDateTime plus(long amountToAdd, TemporalUnit unit): Returns a copy of this date-time with the specified amount added.
- LocalDateTime plus(TemporalAmount amountToAdd): Returns a copy of this date-time with the specified amount added.
- LocalDateTime plusDays(long days): Returns a copy of this LocalDateTime with the specified number of days added.
- LocalDateTime plusHours(long hours): Returns a copy of this LocalDateTime with the specified number of hours added.
- LocalDateTime plusMinutes(long minutes): Returns a copy of this LocalDateTime with the specified number of minutes added.
- LocalDateTime plusMonths(long months): Returns a copy of this LocalDateTime with the specified number of months added.
- LocalDateTime plusNanos(long nanos): Returns a copy of this LocalDateTime with the specified number of nanoseconds added.
- LocalDateTime plusSeconds(long seconds): Returns a copy of this LocalDateTime with the specified number of seconds added.
- LocalDateTime plusWeeks(long weeks): Returns a copy of this LocalDateTime with the specified number of weeks added.
- LocalDateTime plusYears(long years): Returns a copy of this LocalDateTime with the specified number of years added.
import java.time.Duration;
import java.time.LocalDateTime;
import java.time.Period;
import java.time.temporal.ChronoUnit;
public class LocalDateTimeAddSubstractExample {
public static void main(String[] args) {
LocalDateTime localDT = LocalDateTime.parse("1981-10-18T10:20:45");
System.out.println("LocalDateTime : " + localDT);
// Adding/subtracting days
System.out.println("10 days before : " + localDT.minusDays(10));
System.out.println("15 days later : " + localDT.plusDays(15));
// Adding/subtracting months
System.out.println("Minus 4 months : " + localDT.minusMonths(4));
System.out.println("Plus 5 months : " + localDT.plusMonths(5));
// Adding/subtracting weeks
System.out.println("Minus 20 weeks : " + localDT.minusWeeks(20));
System.out.println("Plus 30 weeks : " + localDT.plusWeeks(30));
// Adding/subtracting years
System.out.println("Minus 12 years : " + localDT.minusYears(12));
System.out.println("Plus 4 years : " + localDT.plusYears(4));
// Adding/subtracting hours
System.out.println("12 hours before : " + localDT.minusHours(12));
System.out.println("6 hours later : " + localDT.plusHours(6));
// Adding/subtracting minutes
System.out.println("Minus 40 minutes : " + localDT.minusMinutes(40));
System.out.println("Plus 15 minutes : " + localDT.plusMinutes(15));
// Adding/subtracting seconds
System.out.println("Minus 30 seconds : " + localDT.minusSeconds(30));
System.out.println("Plus 20 seconds : " + localDT.plusSeconds(20));
// Adding/subtracting Nanos
System.out.println("Minus 20000 nanos : " + localDT.minusNanos(20000));
System.out.println("Plus 340000 nanos : " + localDT.plusNanos(340000));
// Using DAYS
System.out.println("30 days before : " + localDT.minus(30, ChronoUnit.DAYS));
// Using WEEKS
System.out.println("3 weeks before : " + localDT.minus(3, ChronoUnit.WEEKS));
// Using MONTHS
System.out.println("6 months later : " + localDT.plus(6, ChronoUnit.MONTHS));
// Using YEARS
System.out.println("2 years later : " + localDT.plus(2, ChronoUnit.YEARS));
// Using HOURS
System.out.println("8 hours before : " + localDT.minus(8, ChronoUnit.HOURS));
// Using MINUTES
System.out.println("35 minutes before : " + localDT.minus(35, ChronoUnit.MINUTES));
// Using SECONDS
System.out.println("125 seconds later : " + localDT.plus(125, ChronoUnit.SECONDS));
// Using NANOS
System.out.println("42357500 nanos later: " + localDT.plus(42357500, ChronoUnit.NANOS));
// Using TemporalAmount - Period
System.out.println("5 years later : " + localDT.plus(Period.ofYears(5)));
// Using TemporalAmount - Duration
System.out.println("60 days before : " + localDT.minus(Duration.ofDays(60)));
System.out.println("160 minutes before : " + localDT.minus(Duration.ofMinutes(160)));
System.out.println("2 hours later : " + localDT.plus(Duration.ofHours(2)));
}
}
LocalDateTime : 1981-10-18T10:20:45 10 days before : 1981-10-08T10:20:45 15 days later : 1981-11-02T10:20:45 Minus 4 months : 1981-06-18T10:20:45 Plus 5 months : 1982-03-18T10:20:45 Minus 20 weeks : 1981-05-31T10:20:45 Plus 30 weeks : 1982-05-16T10:20:45 Minus 12 years : 1969-10-18T10:20:45 Plus 4 years : 1985-10-18T10:20:45 12 hours before : 1981-10-17T22:20:45 6 hours later : 1981-10-18T16:20:45 Minus 40 minutes : 1981-10-18T09:40:45 Plus 15 minutes : 1981-10-18T10:35:45 Minus 30 seconds : 1981-10-18T10:20:15 Plus 20 seconds : 1981-10-18T10:21:05 Minus 20000 nanos : 1981-10-18T10:20:44.999980 Plus 340000 nanos : 1981-10-18T10:20:45.000340 30 days before : 1981-09-18T10:20:45 3 weeks before : 1981-09-27T10:20:45 6 months later : 1982-04-18T10:20:45 2 years later : 1983-10-18T10:20:45 8 hours before : 1981-10-18T02:20:45 35 minutes before : 1981-10-18T09:45:45 125 seconds later : 1981-10-18T10:22:50 42357500 nanos later: 1981-10-18T10:20:45.042357500 5 years later : 1986-10-18T10:20:45 60 days before : 1981-08-19T10:20:45 160 minutes before : 1981-10-18T07:40:45 2 hours later : 1981-10-18T12:20:45
Comparing LocalDateTimes
LocalDateTime class implements interface ChronoLocalDateTime. Following methods can be use to compare two LocalDateTimes:
- int compareTo(ChronoLocalDateTime<?> other): Compares this date-time to another date-time.
- boolean isAfter(ChronoLocalDateTime<?> other): Checks if this date-time is after the specified date-time.
- boolean isBefore(ChronoLocalDateTime<?> other): Checks if this date-time is before the specified date-time.
- boolean isEqual(ChronoLocalDateTime<?> other): Checks if this date-time is equal to the specified date-time.
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
public class LocalDateTimeCompareExample {
public static void main(String[] args) {
LocalDateTime localDT1 = LocalDateTime.parse("1979-12-09T09:50:25");
LocalDateTime localDT2 = LocalDateTime.parse("1980-04-09T09:50:25");
LocalDateTime localDT3 = LocalDateTime.parse("19791209095025", DateTimeFormatter.ofPattern("yyyyMMddHHmmss"));
System.out.println("LocalDateTime1 after LocalDateTime2 : " + localDT1.isAfter(localDT2));
System.out.println("LocalDateTime1 before LocalDateTime2 : " + localDT1.isBefore(localDT2));
System.out.println("LocalDateTime1 equal LocalDateTime3 : " + localDT1.isEqual(localDT3));
System.out.println("LocalDateTime2 equal LocalDateTime3 : " + localDT2.isEqual(localDT3));
System.out.println("LocalDateTime1 compareTo LocalDateTime2: " + localDT1.compareTo(localDT2));
System.out.println("LocalDateTime2 compareTo LocalDateTime1: " + localDT2.compareTo(localDT1));
System.out.println("LocalDateTime1 compareTo LocalDateTime3: " + localDT1.compareTo(localDT3));
System.out.println("LocalDateTime3 compareTo LocalDateTime2: " + localDT3.compareTo(localDT2));
}
}
LocalDateTime1 after LocalDateTime2 : false LocalDateTime1 before LocalDateTime2 : true LocalDateTime1 equal LocalDateTime3 : true LocalDateTime2 equal LocalDateTime3 : false LocalDateTime1 compareTo LocalDateTime2: -1 LocalDateTime2 compareTo LocalDateTime1: 1 LocalDateTime1 compareTo LocalDateTime3: 0 LocalDateTime3 compareTo LocalDateTime2: -1
Supported Field and Unit of a LocalDateTime
Use isSupported(...) to check if a particular field/unit is supported in a LocalDateTime:
- boolean isSupported(TemporalField field): Checks if the specified field is supported.
- boolean isSupported(TemporalUnit unit): Checks if the specified unit is supported.
import java.time.LocalDateTime;
import java.time.temporal.ChronoField;
import java.time.temporal.ChronoUnit;
public class LocalDateTimeIsSupportedExample {
public static void main(String[] args) {
LocalDateTime localDT = LocalDateTime.now();
System.out.println("*** ChronoField ***");
for(ChronoField chronoField : ChronoField.values()){
System.out.println(chronoField + " is supported:" + localDT.isSupported(chronoField));
}
System.out.println("\n*** ChronoUnit ***");
for(ChronoUnit chronoUnit : ChronoUnit.values()){
System.out.println(chronoUnit + " is supported:" + localDT.isSupported(chronoUnit));
}
}
}
*** ChronoField *** NanoOfSecond is supported:true NanoOfDay is supported:true MicroOfSecond is supported:true MicroOfDay is supported:true MilliOfSecond is supported:true MilliOfDay is supported:true SecondOfMinute is supported:true SecondOfDay is supported:true MinuteOfHour is supported:true MinuteOfDay is supported:true HourOfAmPm is supported:true ClockHourOfAmPm is supported:true HourOfDay is supported:true ClockHourOfDay is supported:true AmPmOfDay is supported:true DayOfWeek is supported:true AlignedDayOfWeekInMonth is supported:true AlignedDayOfWeekInYear is supported:true DayOfMonth is supported:true DayOfYear is supported:true EpochDay is supported:true AlignedWeekOfMonth is supported:true AlignedWeekOfYear is supported:true MonthOfYear is supported:true ProlepticMonth is supported:true YearOfEra is supported:true Year is supported:true Era is supported:true InstantSeconds is supported:false OffsetSeconds is supported:false *** ChronoUnit *** Nanos is supported:true Micros is supported:true Millis is supported:true Seconds is supported:true Minutes is supported:true Hours is supported:true HalfDays is supported:true Days is supported:true Weeks is supported:true Months is supported:true Years is supported:true Decades is supported:true Centuries is supported:true Millennia is supported:true Eras is supported:true Forever is supported:false
Convert a LocalDateTime to Another Class
Several methods exists to convert LocalDateTime to another class:
- OffsetDateTime atOffset(ZoneOffset offset): Combines this date-time with an offset to create an OffsetDateTime.
- ZonedDateTime atZone(ZoneId zone): Combines this date-time with a time-zone to create a ZonedDateTime.
- LocalDate toLocalDate(): Gets the LocalDate part of this date-time.
- LocalTime toLocalTime(): Gets the LocalTime part of this date-time.
- Instant toInstant(ZoneOffset offset): Converts this date-time to an Instant.
import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.OffsetDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.time.ZonedDateTime;
public class LocalDateTimeToAnotherClassExample {
public static void main(String[] args) {
LocalDateTime localDT = LocalDateTime.parse("1947-08-07T10:20:45");
System.out.println("LocalDateTime : " + localDT);
OffsetDateTime offsetDateTime = localDT.atOffset(ZoneOffset.UTC);
System.out.println("OffsetDateTime: " + offsetDateTime);
ZonedDateTime zonedDateTime = localDT.atZone(ZoneId.of("Asia/Jakarta"));
System.out.println("ZonedDateTime : " + zonedDateTime);
LocalDate localDate = localDT.toLocalDate();
System.out.println("LocalDate : " + localDate);
LocalTime localTime = localDT.toLocalTime();
System.out.println("LocalTime : " + localTime);
Instant instant = localDT.toInstant(ZoneOffset.UTC);
System.out.println("Instant : " + instant);
}
}
LocalDateTime : 1947-08-07T10:20:45 OffsetDateTime: 1947-08-07T10:20:45Z ZonedDateTime : 1947-08-07T10:20:45+07:30[Asia/Jakarta] LocalDate : 1947-08-07 LocalTime : 10:20:45 Instant : 1947-08-07T10:20:45Z