LocalDateTime
InstancesLocalDateTime
is a class in Java’s Date-Time API that combines date and time into a single object—without any time zone information. It’s useful when you need both parts together, such as scheduling an appointment, timestamping events, or recording logs.
This section shows how to create LocalDateTime
instances using several common approaches: capturing the current date and time, specifying explicit values, or combining separate LocalDate
and LocalTime
objects.
LocalDateTime.now()
The simplest way to get the current date and time is with the now()
method. It retrieves the current date and time from the system clock using the default time zone.
import java.time.LocalDateTime;
public class NowExample {
public static void main(String[] args) {
LocalDateTime current = LocalDateTime.now();
System.out.println("Current DateTime: " + current);
}
}
Output:
Current DateTime: 2025-06-22T14:35:12.123
Use this method for timestamps or capturing when an event occurs.
LocalDateTime.of()
To create a fixed date and time, use of()
. You can provide year, month, day, hour, minute, and optionally second and nanosecond.
LocalDateTime meeting = LocalDateTime.of(2025, 12, 15, 9, 30);
System.out.println("Meeting DateTime: " + meeting);
Output:
Meeting DateTime: 2025-12-15T09:30
This is ideal for scheduling fixed events, deadlines, or future reminders.
You can also specify seconds and nanoseconds if needed:
LocalDateTime preciseTime = LocalDateTime.of(2025, 12, 15, 9, 30, 15, 500_000_000);
System.out.println("Precise DateTime: " + preciseTime);
LocalDate
and LocalTime
If you have separate LocalDate
and LocalTime
instances, you can combine them using atTime()
or LocalDateTime.of()
.
import java.time.LocalDate;
import java.time.LocalTime;
import java.time.LocalDateTime;
public class CombineExample {
public static void main(String[] args) {
LocalDate date = LocalDate.of(2025, 10, 20);
LocalTime time = LocalTime.of(14, 45);
LocalDateTime combined = date.atTime(time);
System.out.println("Combined DateTime: " + combined);
}
}
LocalDateTime
LocalDate
when only the date matters (e.g., birthdays, holidays).LocalTime
when only the time matters (e.g., store opening hours).LocalDateTime
when both date and time are important but without timezone context (e.g., a meeting scheduled for a specific date and time).LocalDateTime
is a convenient choice when your application logic focuses on the local timeline without daylight saving or time zone considerations.
Mastering these creation techniques allows you to work effectively with combined date-time values in Java, setting the foundation for advanced manipulations and formatting.
Once you have a LocalDateTime
instance, it’s often necessary to extract individual date and time components—such as the year, month, day, hour, minute, and second—for display, validation, or decision-making in your application.
Java’s LocalDateTime
class provides simple getter methods to access each part, allowing you to work with the data granularly.
Here is an example that demonstrates how to extract the key parts from a LocalDateTime
object:
import java.time.LocalDateTime;
import java.time.Month;
public class DateTimePartsExample {
public static void main(String[] args) {
LocalDateTime dateTime = LocalDateTime.of(2025, Month.NOVEMBER, 15, 10, 45, 30);
int year = dateTime.getYear();
Month month = dateTime.getMonth();
int day = dateTime.getDayOfMonth();
int hour = dateTime.getHour();
int minute = dateTime.getMinute();
int second = dateTime.getSecond();
System.out.println("Year: " + year);
System.out.println("Month: " + month);
System.out.println("Day: " + day);
System.out.println("Hour: " + hour);
System.out.println("Minute: " + minute);
System.out.println("Second: " + second);
}
}
Output:
Year: 2025
Month: NOVEMBER
Day: 15
Hour: 10
Minute: 45
Second: 30
Conditional Logic: You can apply business rules based on specific parts of the date or time. For example, triggering a special discount if the month is December or restricting access after 6 PM.
if (dateTime.getHour() >= 18) {
System.out.println("After business hours");
}
Custom Formatting: Extracted parts can be combined manually or formatted for reports, logs, or user interfaces.
Validations: Check if the date falls on a weekend by evaluating the day of week (using getDayOfWeek()
), or validate times against business hours.
Accessing individual date and time components from a LocalDateTime
lets you perform precise operations and tailor your application behavior to specific moments in time. The straightforward getter methods ensure your code remains clean and readable while enabling powerful logic based on date-time details.
LocalDateTime
The LocalDateTime
class is immutable, meaning any modification methods return a new instance rather than changing the original. This makes it safe and predictable to perform date-time arithmetic and adjustments without unintended side effects.
Common methods to modify a LocalDateTime
include plusDays()
, minusHours()
, and withMinute()
. These are useful for scenarios such as rescheduling appointments, adjusting deadlines, or calculating follow-up event times.
You can add or subtract days, hours, minutes, and other units to shift the date-time forward or backward.
import java.time.LocalDateTime;
public class ModifyDateTimeExample {
public static void main(String[] args) {
LocalDateTime original = LocalDateTime.of(2025, 7, 10, 14, 30);
// Shift event 3 days later
LocalDateTime shiftedDate = original.plusDays(3);
System.out.println("Shifted Date (plus 3 days): " + shiftedDate);
// Reschedule 2 hours earlier
LocalDateTime earlierTime = original.minusHours(2);
System.out.println("Rescheduled Time (minus 2 hours): " + earlierTime);
}
}
Output:
Shifted Date (plus 3 days): 2025-07-13T14:30
Rescheduled Time (minus 2 hours): 2025-07-10T12:30
The withX()
methods allow you to change specific fields while leaving others unchanged. For example, you might want to change just the minute or day of a scheduled appointment.
LocalDateTime original = LocalDateTime.of(2025, 7, 10, 14, 30);
// Change the minute to 45
LocalDateTime updatedMinute = original.withMinute(45);
System.out.println("Updated Minute: " + updatedMinute);
// Set day to the 1st of the month
LocalDateTime firstOfMonth = original.withDayOfMonth(1);
System.out.println("First of Month: " + firstOfMonth);
Output:
Updated Minute: 2025-07-10T14:45
First of Month: 2025-07-01T14:30
plusDays()
or plusHours()
to calculate the new date and time.minusDays()
or plusMinutes()
can quickly recalculate the new timestamps.withX()
methods to adjust specific time components without affecting the entire date-time, such as changing an appointment from 9:30 to 9:45 AM.Modifying LocalDateTime
instances is simple and intuitive with methods like plusDays()
, minusHours()
, and withMinute()
. Since these methods return new objects, your original data remains safe, while you can flexibly adjust date and time values for a wide range of practical scenarios.
LocalDateTime
Comparing LocalDateTime
instances is essential when managing schedules, deadlines, or event sequences. Java provides clear and intuitive methods—isBefore()
, isAfter()
, and isEqual()
—to compare two LocalDateTime
objects and determine their temporal order.
isBefore()
This method returns true
if the invoking LocalDateTime
occurs strictly before the specified date-time.
Use Case: Check if a deadline has passed.
import java.time.LocalDateTime;
public class CompareExample {
public static void main(String[] args) {
LocalDateTime now = LocalDateTime.now();
LocalDateTime deadline = LocalDateTime.of(2025, 6, 30, 23, 59);
if (now.isBefore(deadline)) {
System.out.println("Deadline not yet reached.");
} else {
System.out.println("Deadline has passed.");
}
}
}
isAfter()
Returns true
if the invoking LocalDateTime
occurs strictly after the specified date-time.
Use Case: Determine if a task was completed after the scheduled start time.
LocalDateTime taskStarted = LocalDateTime.of(2025, 7, 1, 9, 0);
LocalDateTime taskCompleted = LocalDateTime.of(2025, 7, 1, 11, 30);
if (taskCompleted.isAfter(taskStarted)) {
System.out.println("Task finished after it started.");
}
isEqual()
Returns true
if both LocalDateTime
objects represent the exact same date and time.
Use Case: Check if two events occurred simultaneously.
LocalDateTime event1 = LocalDateTime.of(2025, 8, 15, 14, 0);
LocalDateTime event2 = LocalDateTime.of(2025, 8, 15, 14, 0);
if (event1.isEqual(event2)) {
System.out.println("Events occurred at the same time.");
}
isBefore()
and isAfter()
will return false
if the times are equal; use isEqual()
to detect equality.NullPointerException
when calling these methods.Using isBefore()
, isAfter()
, and isEqual()
allows you to implement robust time-based logic—such as enforcing deadlines, ordering events, or detecting overlaps—with concise and readable code. These comparisons form a fundamental part of any application managing date and time.
Converting between LocalDateTime
objects and their string representations is a common requirement in applications—for displaying timestamps, storing data, or parsing user input. Java’s DateTimeFormatter
class provides powerful and flexible tools for this purpose.
LocalDateTime
to StringThe simplest way to format a LocalDateTime
is using predefined formatters like DateTimeFormatter.ISO_LOCAL_DATE_TIME
, which outputs the standard ISO-8601 format:
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
public class FormatExample {
public static void main(String[] args) {
LocalDateTime now = LocalDateTime.now();
// ISO-8601 format
String isoFormatted = now.format(DateTimeFormatter.ISO_LOCAL_DATE_TIME);
System.out.println("ISO format: " + isoFormatted);
}
}
Output example:
ISO format: 2025-06-22T15:30:45.123
You can create custom formatting patterns to suit your needs:
DateTimeFormatter customFormatter = DateTimeFormatter.ofPattern("dd/MM/yyyy HH:mm:ss");
String formatted = now.format(customFormatter);
System.out.println("Custom format: " + formatted);
Output:
Custom format: 22/06/2025 15:30:45
Here, dd
is day of month, MM
is month, yyyy
is year, HH
is 24-hour clock hour, mm
is minutes, and ss
is seconds.
LocalDateTime
Parsing strings back into LocalDateTime
uses the same formatters:
String dateTimeStr = "22/06/2025 15:30:45";
LocalDateTime parsedDateTime = LocalDateTime.parse(dateTimeStr, customFormatter);
System.out.println("Parsed LocalDateTime: " + parsedDateTime);
Output:
Parsed LocalDateTime: 2025-06-22T15:30:45
If you provide an invalid format pattern to DateTimeFormatter.ofPattern()
, it will throw an IllegalArgumentException
immediately. Always verify your pattern strings.
Parsing invalid input strings will throw a DateTimeParseException
. To handle this gracefully:
import java.time.format.DateTimeParseException;
try {
LocalDateTime invalidParse = LocalDateTime.parse("invalid-date", customFormatter);
} catch (DateTimeParseException e) {
System.out.println("Failed to parse date-time: " + e.getMessage());
}
This ensures your program can detect errors and respond appropriately without crashing.
DateTimeFormatter
makes converting LocalDateTime
to and from strings easy and flexible. Use ISO formats for standardization, and custom patterns for specific display or input needs. Always guard against invalid patterns and input with exception handling to make your code robust and user-friendly.