Java LocalDateTime Class
LocalDateTime is an important class in the date-time API introduced in Java 8 (the java.time package). It represents an immutable date-time object without time-zone information. This class can store date-time information with year, month, day, hour, minute, second, and nanosecond precision.
Characteristics of LocalDateTime
- Immutability: All java.time classes are immutable and thread-safe
- No time-zone information: Represents only the local date and time
- Nanosecond precision: Can represent time with nanosecond precision
- Rich API: Provides numerous methods for date-time calculation and formatting
Creating LocalDateTime Objects
1. Using static factory methods
Example
// Get the current date-time
LocalDateTime now = LocalDateTime.now();
// Create using a specified date and time
LocalDateTime specificDateTime = LocalDateTime.of(2023, 5, 15, 14, 30, 45);
// Using year, month, day, hour, minute
LocalDateTime dateTime1 = LocalDateTime.of(2023, Month.MAY, 15, 14, 30);
// Using year, month, day, hour, minute, second
LocalDateTime dateTime2 = LocalDateTime.of(2023, 5, 15, 14, 30, 45);
// Using year, month, day, hour, minute, second, nanosecond
LocalDateTime dateTime3 = LocalDateTime.of(2023, 5, 15, 14, 30, 45, 100);
LocalDateTime now = LocalDateTime.now();
// Create using a specified date and time
LocalDateTime specificDateTime = LocalDateTime.of(2023, 5, 15, 14, 30, 45);
// Using year, month, day, hour, minute
LocalDateTime dateTime1 = LocalDateTime.of(2023, Month.MAY, 15, 14, 30);
// Using year, month, day, hour, minute, second
LocalDateTime dateTime2 = LocalDateTime.of(2023, 5, 15, 14, 30, 45);
// Using year, month, day, hour, minute, second, nanosecond
LocalDateTime dateTime3 = LocalDateTime.of(2023, 5, 15, 14, 30, 45, 100);
2. Combining from LocalDate and LocalTime
Example
LocalDate date = LocalDate.of(2023, 5, 15);
LocalTime time = LocalTime.of(14, 30, 45);
LocalDateTime dateTime = LocalDateTime.of(date, time);
LocalTime time = LocalTime.of(14, 30, 45);
LocalDateTime dateTime = LocalDateTime.of(date, time);
3. Parsing strings
Example
LocalDateTime parsedDateTime = LocalDateTime.parse("2023-05-15T14:30:45");
Common operation methods
Getting date-time components
Example
LocalDateTime dateTime = LocalDateTime.now();
int year = dateTime.getYear();
Month month = dateTime.getMonth(); // Returns the Month enum
int monthValue = dateTime.getMonthValue(); // Returns 1-12
int day = dateTime.getDayOfMonth();
int hour = dateTime.getHour();
int minute = dateTime.getMinute();
int second = dateTime.getSecond();
int nano = dateTime.getNano();
int year = dateTime.getYear();
Month month = dateTime.getMonth(); // Returns the Month enum
int monthValue = dateTime.getMonthValue(); // Returns 1-12
int day = dateTime.getDayOfMonth();
int hour = dateTime.getHour();
int minute = dateTime.getMinute();
int second = dateTime.getSecond();
int nano = dateTime.getNano();
Date-time arithmetic
Example
LocalDateTime dateTime = LocalDateTime.now();
// Addition operations
LocalDateTime plusYears = dateTime.plusYears(1);
LocalDateTime plusMonths = dateTime.plusMonths(1);
LocalDateTime plusDays = dateTime.plusDays(1);
LocalDateTime plusHours = dateTime.plusHours(1);
LocalDateTime plusMinutes = dateTime.plusMinutes(1);
LocalDateTime plusSeconds = dateTime.plusSeconds(1);
// Subtraction operations
LocalDateTime minusYears = dateTime.minusYears(1);
LocalDateTime minusDays = dateTime.minusDays(1);
// Other subtraction operations are similar...
// Addition operations
LocalDateTime plusYears = dateTime.plusYears(1);
LocalDateTime plusMonths = dateTime.plusMonths(1);
LocalDateTime plusDays = dateTime.plusDays(1);
LocalDateTime plusHours = dateTime.plusHours(1);
LocalDateTime plusMinutes = dateTime.plusMinutes(1);
LocalDateTime plusSeconds = dateTime.plusSeconds(1);
// Subtraction operations
LocalDateTime minusYears = dateTime.minusYears(1);
LocalDateTime minusDays = dateTime.minusDays(1);
// Other subtraction operations are similar...
Date-time comparison
Example
LocalDateTime dateTime1 = LocalDateTime.of(2023, 5, 15, 14, 30);
LocalDateTime dateTime2 = LocalDateTime.of(2023, 5, 16, 14, 30);
boolean isBefore = dateTime1.isBefore(dateTime2); // true
boolean isAfter = dateTime1.isAfter(dateTime2); // false
boolean isEqual = dateTime1.isEqual(dateTime2); // false
LocalDateTime dateTime2 = LocalDateTime.of(2023, 5, 16, 14, 30);
boolean isBefore = dateTime1.isBefore(dateTime2); // true
boolean isAfter = dateTime1.isAfter(dateTime2); // false
boolean isEqual = dateTime1.isEqual(dateTime2); // false
Adjusting date and time
Example
LocalDateTime dateTime = LocalDateTime.now();
// Modify specific fields
LocalDateTime withYear = dateTime.withYear(2024);
LocalDateTime withHour = dateTime.withHour(15);
// Other fields are similar...
// Using TemporalAdjusters
LocalDateTime firstDayOfMonth = dateTime.with(TemporalAdjusters.firstDayOfMonth());
LocalDateTime lastDayOfYear = dateTime.with(TemporalAdjusters.lastDayOfYear());
// Modify specific fields
LocalDateTime withYear = dateTime.withYear(2024);
LocalDateTime withHour = dateTime.withHour(15);
// Other fields are similar...
// Using TemporalAdjusters
LocalDateTime firstDayOfMonth = dateTime.with(TemporalAdjusters.firstDayOfMonth());
LocalDateTime lastDayOfYear = dateTime.with(TemporalAdjusters.lastDayOfYear());
Formatting and parsing
Formatting date-time
Example
LocalDateTime dateTime = LocalDateTime.now();
// Using a predefined format
DateTimeFormatter isoDateTime = DateTimeFormatter.ISO_DATE_TIME;
String formatted = dateTime.format(isoDateTime);
// Custom format
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
String customFormatted = dateTime.format(formatter);
// Using a predefined format
DateTimeFormatter isoDateTime = DateTimeFormatter.ISO_DATE_TIME;
String formatted = dateTime.format(isoDateTime);
// Custom format
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
String customFormatted = dateTime.format(formatter);
Parsing a string into date-time
Example
String str = "2023-05-15 14:30:45";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
LocalDateTime parsedDateTime = LocalDateTime.parse(str, formatter);
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
LocalDateTime parsedDateTime = LocalDateTime.parse(str, formatter);
Conversions with other date-time classes
Converting to LocalDate and LocalTime
Example
LocalDateTime dateTime = LocalDateTime.now();
LocalDate date = dateTime.toLocalDate();
LocalTime time = dateTime.toLocalTime();
LocalDate date = dateTime.toLocalDate();
LocalTime time = dateTime.toLocalTime();
Conversion with Instant and ZonedDateTime
Example
// Time-zone information required
ZoneId zone = ZoneId.systemDefault();
// Convert LocalDateTime to ZonedDateTime
ZonedDateTime zonedDateTime = dateTime.atZone(zone);
// Convert ZonedDateTime to LocalDateTime
LocalDateTime fromZoned = zonedDateTime.toLocalDateTime();
// Convert LocalDateTime to Instant
Instant instant = zonedDateTime.toInstant();
// Convert Instant to LocalDateTime
LocalDateTime fromInstant = LocalDateTime.ofInstant(instant, zone);
ZoneId zone = ZoneId.systemDefault();
// Convert LocalDateTime to ZonedDateTime
ZonedDateTime zonedDateTime = dateTime.atZone(zone);
// Convert ZonedDateTime to LocalDateTime
LocalDateTime fromZoned = zonedDateTime.toLocalDateTime();
// Convert LocalDateTime to Instant
Instant instant = zonedDateTime.toInstant();
// Convert Instant to LocalDateTime
LocalDateTime fromInstant = LocalDateTime.ofInstant(instant, zone);
Practical application examples
Calculating the interval between two date-times
Example
LocalDateTime start = LocalDateTime.of(2023, 5, 15, 9, 0);
LocalDateTime end = LocalDateTime.of(2023, 5, 16, 17, 30);
Duration duration = Duration.between(start, end);
long hours = duration.toHours(); // 32
long minutes = duration.toMinutes(); // 1950
LocalDateTime end = LocalDateTime.of(2023, 5, 16, 17, 30);
Duration duration = Duration.between(start, end);
long hours = duration.toHours(); // 32
long minutes = duration.toMinutes(); // 1950
Checking if a date is within a specific range
Example
LocalDateTime checkDate = LocalDateTime.of(2023, 5, 15, 14, 0);
LocalDateTime startDate = LocalDateTime.of(2023, 5, 1, 0, 0);
LocalDateTime endDate = LocalDateTime.of(2023, 5, 31, 23, 59);
boolean isInRange = !checkDate.isBefore(startDate) && !checkDate.isAfter(endDate);
LocalDateTime startDate = LocalDateTime.of(2023, 5, 1, 0, 0);
LocalDateTime endDate = LocalDateTime.of(2023, 5, 31, 23, 59);
boolean isInRange = !checkDate.isBefore(startDate) && !checkDate.isAfter(endDate);
Generating a date-time sequence
Example
LocalDateTime start = LocalDateTime.of(2023, 5, 1, 9, 0);
List<LocalDateTime> dateTimes = new ArrayList<>();
for (int i = 0; i < 10; i++) {
dateTimes.add(start.plusDays(i));
}
List<LocalDateTime> dateTimes = new ArrayList<>();
for (int i = 0; i < 10; i++) {
dateTimes.add(start.plusDays(i));
}
Comprehensive example
Example
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
public class LocalDateTimeDemo {
public static void main(String[] args) {
// 1. Get the current date-time
LocalDateTime now = LocalDateTime.now();
System.out.println("Current date-time: " + now);
// 2. Create a specific date-time
LocalDateTime specificDateTime = LocalDateTime.of(2023, 5, 15, 10, 30, 45);
System.out.println("Specific date-time: " + specificDateTime);
// 3. Parse from a string
LocalDateTime parsedDateTime = LocalDateTime.parse("2023-05-15T10:30:45");
System.out.println("Parsed date-time: " + parsedDateTime);
// 4. Format output
DateTimeFormatter formatter = DateTimeFormatter.ofPattern(yyyy-MM-dd HH:mm:ss);
String formattedDateTime = now.format(formatter);
System.out.println("Formatted date-time: " + formattedDateTime);
// 5. Get each component
System.out.println("Year: " + now.getYear());
System.out.println("Month: " + now.getMonthValue() + " (" + now.getMonth() + ")");
System.out.println("Day: " + now.getDayOfMonth());
System.out.println("Hour: " + now.getHour());
System.out.println("Minute: " + now.getMinute());
System.out.println("Second: " + now.getSecond());
// 6. Date-time operations
LocalDateTime tomorrow = now.plusDays(1);
System.out.println("Tomorrow at this time: " + tomorrow);
LocalDateTime lastWeek = now.minusWeeks(1);
System.out.println("Last week at this time: " + lastWeek);
// 7. Compare date-times
System.out.println("Is now after the specific time: " + now.isAfter(specificDateTime));
System.out.println("Is now before the specific time: " + now.isBefore(specificDateTime));
}
}
import java.time.format.DateTimeFormatter;
public class LocalDateTimeDemo {
public static void main(String[] args) {
// 1. Get the current date-time
LocalDateTime now = LocalDateTime.now();
System.out.println("Current date-time: " + now);
// 2. Create a specific date-time
LocalDateTime specificDateTime = LocalDateTime.of(2023, 5, 15, 10, 30, 45);
System.out.println("Specific date-time: " + specificDateTime);
// 3. Parse from a string
LocalDateTime parsedDateTime = LocalDateTime.parse("2023-05-15T10:30:45");
System.out.println("Parsed date-time: " + parsedDateTime);
// 4. Format output
DateTimeFormatter formatter = DateTimeFormatter.ofPattern(yyyy-MM-dd HH:mm:ss);
String formattedDateTime = now.format(formatter);
System.out.println("Formatted date-time: " + formattedDateTime);
// 5. Get each component
System.out.println("Year: " + now.getYear());
System.out.println("Month: " + now.getMonthValue() + " (" + now.getMonth() + ")");
System.out.println("Day: " + now.getDayOfMonth());
System.out.println("Hour: " + now.getHour());
System.out.println("Minute: " + now.getMinute());
System.out.println("Second: " + now.getSecond());
// 6. Date-time operations
LocalDateTime tomorrow = now.plusDays(1);
System.out.println("Tomorrow at this time: " + tomorrow);
LocalDateTime lastWeek = now.minusWeeks(1);
System.out.println("Last week at this time: " + lastWeek);
// 7. Compare date-times
System.out.println("Is now after the specific time: " + now.isAfter(specificDateTime));
System.out.println("Is now before the specific time: " + now.isBefore(specificDateTime));
}
}
The output is:
格式化后的日期时间: 2025年05月01日 11:25:48 年: 2025 月: 5 (MAY) 日: 1 时: 11 分: 25 秒: 48 明天此时: 2025-05-02T11:25:48.651400 上周此时: 2025-04-24T11:25:48.651400 现在是否在特定时间之后: true 现在是否在特定时间之前: false
Date-time conversion
Example
import java.time.*;
public class DateTimeConversion {
public static void main(String[] args) {
// Convert LocalDateTime to LocalDate and LocalTime
LocalDateTime dateTime = LocalDateTime.now();
LocalDate date = dateTime.toLocalDate();
LocalTime time = dateTime.toLocalTime();
System.out.println("Date part: " + date);
System.out.println("Time part: " + time);
// Create LocalDateTime from LocalDate and LocalTime
LocalDateTime combined = LocalDateTime.of(date, time);
System.out.println("Combined date-time: " + combined);
// Convert with Instant (requires time zone)
ZoneId zone = ZoneId.of("Asia/Shanghai");
Instant instant = dateTime.atZone(zone).toInstant();
System.out.println("Converted to Instant: " + instant);
}
}
public class DateTimeConversion {
public static void main(String[] args) {
// Convert LocalDateTime to LocalDate and LocalTime
LocalDateTime dateTime = LocalDateTime.now();
LocalDate date = dateTime.toLocalDate();
LocalTime time = dateTime.toLocalTime();
System.out.println("Date part: " + date);
System.out.println("Time part: " + time);
// Create LocalDateTime from LocalDate and LocalTime
LocalDateTime combined = LocalDateTime.of(date, time);
System.out.println("Combined date-time: " + combined);
// Convert with Instant (requires time zone)
ZoneId zone = ZoneId.of("Asia/Shanghai");
Instant instant = dateTime.atZone(zone).toInstant();
System.out.println("Converted to Instant: " + instant);
}
}
The output is:
日期部分: 2025-05-01 时间部分: 11:27:02.724101 组合后的日期时间: 2025-05-01T11:27:02.724101 转换为Instant: 2025-05-01T03:27:02.724101Z
Summary
The LocalDateTime class is a very practical class in the Java 8 date-time API. It provides rich methods for handling dates and times without time zones. Through this article, you should have mastered:
- How to create LocalDateTime objects
- How to perform date-time calculations and comparisons
- How to format and parse date-time
- How to convert with other date-time classes
- Some practical application scenarios
LocalDateTime is very suitable for business scenarios that do not require time-zone information, such as birthdays and meeting times. For scenarios requiring time-zone handling, consider using the ZonedDateTime class.
Static factory methods
| Method | Description | Example |
|---|---|---|
static LocalDateTime now() |
Get the current date-time | LocalDateTime.now() |
static LocalDateTime of(int year, int month, int day, int hour, int minute) |
Create with specified year, month, day, hour, minute | LocalDateTime.of(2023, 6, 15, 14, 30) |
static LocalDateTime of(int year, int month, int day, int hour, int minute, int second) |
Create with specified year, month, day, hour, minute, second | LocalDateTime.of(2023, 6, 15, 14, 30, 45) |
static LocalDateTime of(int year, Month month, int day, int hour, int minute) |
Create using the Month enum | LocalDateTime.of(2023, Month.JUNE, 15, 14, 30) |
static LocalDateTime of(LocalDate date, LocalTime time) |
Create by combining LocalDate and LocalTime | LocalDateTime.of(LocalDate.now(), LocalTime.now()) |
static LocalDateTime parse(CharSequence text) |
Parse from string (ISO format) | LocalDateTime.parse("2023-06-15T14:30:45") |
static LocalDateTime parse(CharSequence text, DateTimeFormatter formatter) |
Parse using a specified format | LocalDateTime.parse("15/06/2023 14:30", DateTimeFormatter.ofPattern("dd/MM/yyyy HH:mm")) |
Getting date-time information
| Method | Description | Example |
|---|---|---|
int getYear() |
Get year | 2023 |
Month getMonth() |
Get month (Month enum) | Month.JUNE |
int getMonthValue() |
Get month value (1-12) | 6 |
int getDayOfMonth() |
Get day of month | 15 |
int getDayOfYear() |
Get day of year | 166 |
DayOfWeek getDayOfWeek() |
Get day of week (DayOfWeek enum) | DayOfWeek.THURSDAY |
int getHour() |
Get hour (0-23) | 14 |
int getMinute() |
Get minute (0-59) | 30 |
int getSecond() |
Get second (0-59) | 45 |
int getNano() |
Get nanosecond | 0 |
Date-time operations
| Method | Description | Example |
|---|---|---|
LocalDateTime plusDays(long days) |
Add days | dt.plusDays(5) |
LocalDateTime plusHours(long hours) |
Add hours | dt.plusHours(2) |
LocalDateTime plusMinutes(long minutes) |
Add minutes | dt.plusMinutes(30) |
LocalDateTime plusSeconds(long seconds) |
Add seconds | dt.plusSeconds(45) |
LocalDateTime plusNanos(long nanos) |
Add nanoseconds | dt.plusNanos(1000000) |
LocalDateTime minusDays(long days) |
Subtract days | dt.minusDays(5) |
LocalDateTime minusHours(long hours) |
Subtract hours | dt.minusHours(2) |
LocalDateTime minusMinutes(long minutes) |
Subtract minutes | dt.minusMinutes(30) |
LocalDateTime minusSeconds(long seconds) |
Subtract seconds | dt.minusSeconds(45) |
LocalDateTime minusNanos(long nanos) |
Subtract nanoseconds | dt.minusNanos(1000000) |
LocalDateTime withYear(int year) |
Modify year | dt.withYear(2024) |
LocalDateTime withMonth(int month) |
Modify month | dt.withMonth(12) |
LocalDateTime withDayOfMonth(int day) |
Modify day of month | dt.withDayOfMonth(1) |
LocalDateTime withHour(int hour) |
Modify hour | dt.withHour(0) |
LocalDateTime withMinute(int minute) |
Modify minute | dt.withMinute(0) |
LocalDateTime withSecond(int second) |
Modify second | dt.withSecond(0) |
LocalDateTime withNano(int nano) |
Modify nanosecond | dt.withNano(0) |
Date-time comparison
| Method | Description | Example |
|---|---|---|
boolean isAfter(ChronoLocalDateTime<?> other) |
Whether it is after the specified date-time | dt1.isAfter(dt2) |
boolean isBefore(ChronoLocalDateTime<?> other) |
Whether it is before the specified date-time | dt1.isBefore(dt2) |
boolean isEqual(ChronoLocalDateTime<?> other) |
Whether it equals the specified date-time | dt1.isEqual(dt2) |
int compareTo(ChronoLocalDateTime<?> other) |
Compare two date-times | dt1.compareTo(dt2) |
Conversion methods
| Method | Description | Example |
|---|---|---|
LocalDate toLocalDate() |
Convert to LocalDate | dt.toLocalDate() |
LocalTime toLocalTime() |
Convert to LocalTime | dt.toLocalTime() |
Instant toInstant(ZoneOffset offset) |
Convert to Instant | dt.toInstant(ZoneOffset.UTC) |
ZonedDateTime atZone(ZoneId zone) |
Convert to ZonedDateTime | dt.atZone(ZoneId.of("Asia/Shanghai")) |
OffsetDateTime atOffset(ZoneOffset offset) |
Convert to OffsetDateTime | dt.atOffset(ZoneOffset.ofHours(8)) |
Formatting and string conversion
| Method | Description | Example |
|---|---|---|
String format(DateTimeFormatter formatter) |
Format as string | dt.format(DateTimeFormatter.ISO_DATE_TIME) |
String toString() |
Convert to ISO format string | "2023-06-15T14:30:45" |