Sobes.tech
Junior

What is LocalDateTime in Java?

sobes.tech AI

Answer from AI

LocalDateTime is an immutable class in the java.time package that represents date and time without a time zone. It stores the date in the format year-month-day and time in hours-minutes-seconds-nanoseconds.

Main methods and features:

  • Creation:

    • now(): Gets the current date and time based on system clocks.
    • of(int year, int month, int dayOfMonth, int hour, int minute, int second, int nanoOfSecond): Creates an instance with specified components.
    • parse(CharSequence text): Parses a string in ISO 8601 format (yyyy-MM-dd'T'HH:mm:ss).
    // Creating LocalDateTime examples
    LocalDateTime now = LocalDateTime.now();
    LocalDateTime specific = LocalDateTime.of(2023, 10, 26, 10, 30, 0, 0);
    LocalDateTime parsed = LocalDateTime.parse("2023-10-26T10:30:00");
    
  • Getting components:

    • getYear(), getMonth(), getDayOfMonth(), getHour(), getMinute(), getSecond(), getNano(): Extract individual parts of date and time.
  • Manipulations:

    • plusYears(), plusMonths(), plusDays(), plusHours(), plusMinutes(), plusSeconds(), plusNanos(): Adding intervals.
    • minusYears(), minusMonths(), minusDays(), minusHours(), minusMinutes(), minusSeconds(), minusNanos(): Subtracting intervals.
    • withYear(), withMonth(), withDayOfMonth(), withHour(), withMinute(), withSecond(), withNano(): Creating a new instance with a modified component.
    // Manipulating LocalDateTime
    LocalDateTime future = now.plusHours(3).minusMinutes(15);
    LocalDateTime modified = now.withYear(2024);
    
  • Comparison:

    • isAfter(), isBefore(), isEqual(): Comparing with another LocalDateTime.
  • Conversion:

    • toLocalDate(): Gets only the date.
    • toLocalTime(): Gets only the time.
    • atZone(ZoneId zone): Converts to ZonedDateTime (considering time zone).
    // Conversions
    LocalDate datePart = now.toLocalDate();
    LocalTime timePart = now.toLocalTime();
    ZonedDateTime zonedDateTime = now.atZone(ZoneId.systemDefault());
    

LocalDateTime does not contain information about time zone and UTC offset, making it suitable for storing dates and times where these aspects are not important or are determined by the application context. For working with specific moments in different time zones, ZonedDateTime or OffsetDateTime should be used.