Module 4: LocalDateTime

Module Overview

Learn about LocalDateTime in Java, a powerful class for working with dates and times without timezone information. Understand how to create, manipulate, format, and compare date-time objects in your applications.

Learning Objectives

  • Understand what LocalDateTime objects are
  • Know how to use LocalDateTime to:
    • Get the current date and time
    • Create an object representative of a specific date
  • Know how to compare between other times and dates
  • Know how to add and remove amounts of time from a LocalDateTime object
  • Understand ZonedDateTime and how to covert between LocalDateTime to compensate for timezones

Working with LocalDateTime

In Java, the LocalDateTime class represents a date-time without a timezone, like 2022-04-25T10:15:30. It's part of the java.time package introduced in Java 8, which provides a comprehensive date and time API that is both simple to use and powerful.

Creating LocalDateTime Objects

There are several ways to create LocalDateTime objects:

// Get the current date and time
LocalDateTime now = LocalDateTime.now();

// Create a specific date and time
LocalDateTime dateTime = LocalDateTime.of(2022, 4, 25, 10, 15, 30);

// Parse a string to LocalDateTime
LocalDateTime parsed = LocalDateTime.parse("2022-04-25T10:15:30");

Comparing LocalDateTime Objects

LocalDateTime provides methods for comparing date-time objects:

LocalDateTime now = LocalDateTime.now();
LocalDateTime pastDate = now.minusDays(5);
LocalDateTime futureDate = now.plusDays(5);

// Check if now is after pastDate
boolean isAfter = now.isAfter(pastDate);  // true

// Check if now is before futureDate
boolean isBefore = now.isBefore(futureDate);  // true

// Check if two dates are equal
boolean isEqual = now.isEqual(now);  // true

Manipulating LocalDateTime Objects

LocalDateTime objects are immutable, but you can create new objects with modifications:

LocalDateTime now = LocalDateTime.now();

// Adding time
LocalDateTime future = now.plusYears(1)
                          .plusMonths(2)
                          .plusDays(3)
                          .plusHours(4)
                          .plusMinutes(5)
                          .plusSeconds(6);

// Subtracting time
LocalDateTime past = now.minusYears(1)
                        .minusMonths(2)
                        .minusDays(3)
                        .minusHours(4)
                        .minusMinutes(5)
                        .minusSeconds(6);

// With specific field values
LocalDateTime withFields = now.withYear(2025)
                             .withMonth(Month.JULY.getValue())
                             .withDayOfMonth(15)
                             .withHour(10)
                             .withMinute(30)
                             .withSecond(0);

Formatting LocalDateTime

You can format LocalDateTime objects in various ways:

LocalDateTime dateTime = LocalDateTime.of(2022, 4, 25, 10, 15, 30);

// Using predefined formats
String iso = dateTime.toString();  // 2022-04-25T10:15:30

// Using DateTimeFormatter
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MM-yyyy HH:mm:ss");
String formatted = dateTime.format(formatter);  // 25-04-2022 10:15:30

// Other formatting examples
String formatDay = dateTime.format(DateTimeFormatter.ofPattern("EEEE, MMMM dd, yyyy"));  // Monday, April 25, 2022
String formatTime = dateTime.format(DateTimeFormatter.ofPattern("hh:mm a"));  // 10:15 AM

Working with Time Zones

LocalDateTime doesn't have timezone information. For timezone-aware date-time operations, you can convert to ZonedDateTime:

LocalDateTime localDateTime = LocalDateTime.now();

// Convert to a specific zone
ZoneId newYorkZone = ZoneId.of("America/New_York");
ZonedDateTime newYorkTime = localDateTime.atZone(newYorkZone);

// Convert to a different zone
ZoneId tokyoZone = ZoneId.of("Asia/Tokyo");
ZonedDateTime tokyoTime = newYorkTime.withZoneSameInstant(tokyoZone);

// Get the offset
ZoneOffset offset = tokyoTime.getOffset();

// Display with timezone
String zonedFormatted = tokyoTime.format(
    DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss z")
);  // 2022-04-26 00:15:30 JST

Guided Projects

Mastery Task 4: Converting to LocalDateTime

Mastery Task Guidelines

Mastery Tasks are opportunities to test your knowledge and understanding through code. When a mastery task is shown in a module, it means that we've covered all the concepts that you need to complete that task.

Each mastery task must pass 100% of the automated tests and code styling checks to pass each sprint. Your code must be your own. If you have any questions, feel free to reach out for support.

Working with GSON and LocalDateTime Objects

Right now the postedon field in the Post class is of type String. Eventually, we'd like to perform logic with this field and so it needs to be converted to a LocalDateTime object. You will notice that by default, GSON has issues converting a LocalDateTime to JSON. Use a typeAdapter and the LocalDateTimeAdapter class to help GSON with the conversion.

Completion

Once this is working MT04_LocalDateTime tests should all pass.

./gradlew -q clean :test --tests 'com.bloomtech.socialfeed.MT04*'

Resources