January 6, 2023

LocalDateTime in Java With Examples

The java.time.LocalDateTime class is part of new date and time API added in Java 8 that represents a date-time in the ISO-8601 calendar system, such as 2019-10-03T11:15:35, it represents a date-time, often viewed as year-month-day-hour-minute-second. LocalDateTime class does not store or represent a time-zone. Instead, it is a description of the date, as used for birthdays, combined with the local time as seen on a wall clock.

LocalDateTime class is immutable thus thread-safe. Since it is marked as final so can't be extended. In this post we’ll see some examples demonstrating usage of Java LocalDateTime class.

Creating instances of LocalDateTime

LocalDateTime class in Java doesn't have any public constructors to obtain an instance, you will use a factory method to get an instance.

1. Using now() method you can obtain the current date-time from the system clock in the default time-zone.

LocalDateTime dateTime = LocalDateTime.now();
System.out.println(dateTime); //2019-10-30T10:29:37.082914100

2. Using of() method you can create an instance of LocalDateTime by passing both year, month, day and hour, minute, second values.

There is also an of() method to create an instance of LocalDateTime by passing both LocalDate and LocalTime instances.

  • of(LocalDate date, LocalTime time)
LocalDateTime dateTime = LocalDateTime.of(2019, 10, 28, 11, 59, 59);
System.out.println(dateTime); //2019-10-28T11:59:59

LocalDateTime for specific time-zone

You can also obtain the current date-time from the system clock in the specified time-zone by passing the zone id.

ZoneId zone1 = ZoneId.of("America/Los_Angeles");
ZoneId zone2 = ZoneId.of("Asia/Kolkata");
LocalDateTime ldt1 = LocalDateTime.now(zone1);
LocalDateTime ldt2 = LocalDateTime.now(zone2);

System.out.println(ldt1); //2019-10-29T22:05:57.729368200
System.out.println(ldt2); //2019-10-30T10:35:57.827541900

Getting date and time values from LocalDateTime

Since LocalDateTime has both date and time values so it has methods to get year, month, day values as well as methods to get hour, minute, second values too.

public class FormatDate {
  public static void main(String[] args) {
    LocalDateTime dateTime = LocalDateTime.of(2019, 10, 28, 11, 59, 59);
    System.out.println("Date-Time: " + dateTime);
    
    System.out.println("Year- " + dateTime.getYear());
    System.out.println("Month- " + dateTime.getMonthValue());
    System.out.println("Day- " + dateTime.getDayOfMonth());
    
    System.out.println("Hour- " + dateTime.getHour());
    System.out.println("Minute- " + dateTime.getMinute());
    System.out.println("Second- " + dateTime.getSecond());
  }
}
Output
Date-Time: 2019-10-28T11:59:59
Year- 2019
Month- 10
Day- 28
Hour- 11
Minute- 59
Second- 59

Formatting LocalDateTime

Using DateTimeFormatter you can specify the pattern for formatting LocalDateTime.

public class FormatDate {
  public static void main(String[] args) {
    // get datetime
    LocalDateTime dateTime = LocalDateTime.now();
    // Format pattern
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS");
    System.out.println(dateTime.format(formatter));
    // Format pattern
    formatter = DateTimeFormatter.ofPattern("cccc, MMM dd, yyyy hh:mm:ss a");
    System.out.println(dateTime.format(formatter));
  }
}
Output
2019-10-30T11:06:51.899
Wednesday, Oct 30, 2019 11:06:51 AM

Date calculations using LocalDateTime

There are methods to add or subtract days, months and years from a LocalDateTime.

public class FormatDate {
  public static void main(String[] args) {
    // get datetime
    LocalDateTime dateTime = LocalDateTime.now();

    System.out.println("Created Date-Time: " + dateTime);  
    System.out.println("Date after subtraction - " + dateTime.minusDays(40));
    System.out.println("Date after year subtraction - " + dateTime.minusYears(2));
     
    System.out.println("Date after addition - " + dateTime.plusDays(40));
    System.out.println("Date after year addition - " + dateTime.plusYears(2));
  }
}
Output
Created Date-Time: 2019-10-30T11:11:06.820635900
Date after subtraction - 2019-09-20T11:11:06.820635900
Date after year subtraction - 2017-10-30T11:11:06.820635900
Date after addition - 2019-12-09T11:11:06.820635900
Date after year addition – 2021-10-30T11:11:06.820635900

Time calculations using LocalDateTime

There are methods to add or subtract hours, minutes, seconds, nano seconds from a LocalDateTime.

public class FormatDate {
  public static void main(String[] args) {
    // get datetime
    LocalDateTime dateTime = LocalDateTime.now();

    System.out.println("Created Date-Time: " + dateTime);  

    System.out.println("Hour after subtraction- " + dateTime.minusHours(2));
    System.out.println("Minute after subtraction- " + dateTime.minusMinutes(10));
    System.out.println("Second after subtraction- " + dateTime.minusSeconds(20));
    System.out.println("NanoSecond after subtraction- " + dateTime.minusNanos(100));

    System.out.println("Hour after addition- " + dateTime.plusHours(1));
    System.out.println("Minute after addition- " + dateTime.plusMinutes(15));
    System.out.println("Second after addition- " + dateTime.plusSeconds(25));
    System.out.println("NanoSecond after addition- " + dateTime.plusNanos(100));
  }
}
Output
Created Date-Time: 2019-10-30T11:14:07.632356
Hour after subtraction- 2019-10-30T09:14:07.632356
Minute after subtraction- 2019-10-30T11:04:07.632356
Second after subtraction- 2019-10-30T11:13:47.632356
NanoSecond after subtraction- 2019-10-30T11:14:07.632355900
Hour after addition- 2019-10-30T12:14:07.632356
Minute after addition- 2019-10-30T11:29:07.632356
Second after addition- 2019-10-30T11:14:32.632356
NanoSecond after addition- 2019-10-30T11:14:07.632356100

Comparing LocalDateTimes in Java

For comparing two LocalDateTime instances there are the following methods-

  • compareTo(ChronoLocalDateTime<?> other)- Compares this date-time to another date-time. Returns negative value if less than tha passed LocalDateTime instance, positive if greater.
  • isAfter(ChronoLocalDateTime<?> other)- Checks if this date-time is after the specified date-time.
  • isBefore(ChronoLocalDateTime<?> other)- Checks if this date-time is before the specified date-time.
  • isEqual(ChronoLocalDateTime<?> other)- Checks if this date-time is equal to the specified date-time.
public class FormatDate {
  public static void main(String[] args) {
    // get datetime
    LocalDateTime ldt1 = LocalDateTime.of(2019, Month.OCTOBER, 25, 20, 25, 45);
    LocalDateTime ldt2 = LocalDateTime.of(2019, Month.SEPTEMBER, 20, 22, 18, 40);

    System.out.println("Created Date-Time1: " + ldt1);  
    System.out.println("Created Date-Time2: " + ldt2);

    System.out.println(ldt1.compareTo(ldt2));
    System.out.println(ldt2.compareTo(ldt1));

    System.out.println(ldt1.isAfter(ldt2));
    System.out.println(ldt1.isBefore(ldt2));
    System.out.println(ldt1.isEqual(ldt2));
  }
}
Output
Created Date-Time1: 2019-10-25T20:25:45
Created Date-Time2: 2019-09-20T22:18:40
1
-1
true
false
false

Converting String to LocalDateTime

Check this post for String to LocalDateTime conversion- Convert String to Date in Java

Converting LocalDateTime to String

Check this post for LocalDateTime to String conversion- Convert Date to String in Java

That's all for the topic LocalDateTime in Java With Examples. If something is missing or you have something to share about the topic please write a comment.


You may also like

No comments:

Post a Comment