Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Java LocalDateTime Class

Java LocalDateTime Class

LocalDateTime is an important class in the Date and Time API (java.time package) introduced in Java 8. It represents an immutable date-time object without time-zone information. This class can store date-time information at the level of year, month, day, hour, minute, second, and nanosecond.

Features of LocalDateTime

  1. Immutability: All java.time classes are immutable and thread-safe
  2. No time zone: Only represents local date and time
  3. Precise to nanoseconds: Can represent time precise to the nanosecond level
  4. Rich API: Provides a large number of methods for date-time calculation and formatting

Creating a LocalDateTime object

1. Use static factory methods

Example

package), which solves many problems of the Date class:

LocalDateTime now

=

LocalDateTime.

now

(

)

;

// Create with specified date and time

LocalDateTime specificDateTime

=

LocalDateTime.

of

(

2023

,

5

,

15

,

14

,

30

,

45

)

;

// Use year, month, day, hour, minute

LocalDateTime dateTime1

=

LocalDateTime.

of

(

2023

, Month.

MAY

,

15

,

14

,

30

)

;

// Use year, month, day, hour, minute, second

LocalDateTime dateTime2

=

LocalDateTime.

of

(

2023

,

5

,

15

,

14

,

30

,

45

)

;

// Use year, month, day, hour, minute, second, nanosecond

LocalDateTime dateTime3

=

LocalDateTime.

of

(

2023

,

5

,

15

,

14

,

30

,

45

,

100

)

;

2. Combine 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

)

;

3. Parse a string

Example

LocalDateTime parsedDateTime

=

LocalDateTime.

parse

(

"2023-05-15T14:30:45"

)

;


Common operation methods

Get each part of the date-time

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

(

)

;

Date-time calculation

Example

LocalDateTime dateTime

=

LocalDateTime.

now

(

)

;

// Add 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

)

;

// Subtract operations

LocalDateTime minusYears

=

dateTime.

minusYears

(

1

)

;

LocalDateTime minusDays

=

dateTime.

minusDays

(

1

)

;

// Other subtract 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

Adjust the date-time

Example

LocalDateTime dateTime

=

LocalDateTime.

now

(

)

;

// Modify specific fields

LocalDateTime withYear

=

dateTime.

withYear

(

2024

)

;

LocalDateTime withHour

=

dateTime.

withHour

(

15

)

;

// Other fields are similar...

// Use TemporalAdjusters

LocalDateTime firstDayOfMonth

=

dateTime.

with

(

TemporalAdjusters.

firstDayOfMonth

(

)

)

;

LocalDateTime lastDayOfYear

=

dateTime.

with

(

TemporalAdjusters.

lastDayOfYear

(

)

)

;


Formatting and parsing

Format the date-time

Example

LocalDateTime dateTime

=

LocalDateTime.

now

(

)

;

// Use predefined formats

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

)

;

Parse 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

)

;


Conversion with other date-time classes

Convert to LocalDate and LocalTime

Example

LocalDateTime dateTime

=

LocalDateTime.

now

(

)

;

LocalDate date

=

dateTime.

toLocalDate

(

)

;

LocalTime time

=

dateTime.

toLocalTime

(

)

;

Conversion with Instant and ZonedDateTime

Example

// Time zone information needed

ZoneId zone

=

ZoneId.

systemDefault

(

)

;

// LocalDateTime to ZonedDateTime

ZonedDateTime zonedDateTime

=

dateTime.

atZone

(

zone

)

;

// ZonedDateTime to LocalDateTime

LocalDateTime fromZoned

=

zonedDateTime.

toLocalDateTime

(

)

;

// LocalDateTime to Instant

Instant instant

=

zonedDateTime.

toInstant

(

)

;

// Instant to LocalDateTime

LocalDateTime fromInstant

=

LocalDateTime.

ofInstant

(

instant, zone

)

;


Practical Application Examples

Calculate 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

Check whether 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

)

;

Generate a sequence of date-times

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

)

)

;

}

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 and time: "

now

)

;

       

       

// 2. Create a specific date-time

        LocalDateTime specificDateTime

=

LocalDateTime.

of

(

2023

,

5

,

15

,

10

,

30

,

45

)

;

       

System

.

out

.

println

(

"Specific date and 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 part

       

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 arithmetic

        LocalDateTime tomorrow

=

now.

plusDays

(

1

)

;

       

System

.

out

.

println

(

"Same time tomorrow: "

tomorrow

)

;

       

        LocalDateTime lastWeek

=

now.

minusWeeks

(

1

)

;

       

System

.

out

.

println

(

"Same time last week: "

lastWeek

)

;

       

       

// 7. Compare date-times

       

System

.

out

.

println

(

"Is now after a specific time: "

now.

isAfter

(

specificDateTime

)

)

;

       

System

.

out

.

println

(

"Is now before a 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

)

{

       

// LocalDateTime converted 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

)

;

       

       

// Conversion with Instant (time zone required)

        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 and Time API. It provides rich methods for handling date and time without a time zone. After studying this article, you should have mastered:

  1. How to create LocalDateTime objects
  2. How to perform date-time calculation and comparison
  3. How to format and parse date-time
  4. How to convert with other date-time classes
  5. Some practical application scenarios

LocalDateTime is very suitable for business scenarios that do not need time-zone information, such as birthdays and meeting times. For scenarios that require time-zone handling, you should consider using the ZonedDateTime class.

Static factory methods

Method Description Example
static LocalDateTime now() Get Current Date and 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 a 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"))

Get date-time information

Method Description Example
int getYear() Get the year 2023
Month getMonth() Get the month (Month enum) Month.JUNE
int getMonthValue() Get the month value (1-12) 6
int getDayOfMonth() Get the day of the month 15
int getDayOfYear() Get the day of the year 166
DayOfWeek getDayOfWeek() Get the day of the week (DayOfWeek enum) DayOfWeek.THURSDAY
int getHour() Get the hour (0-23) 14
int getMinute() Get the minute (0-59) 30
int getSecond() Get the second (0-59) 45
int getNano() Get the 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 the year dt.withYear(2024)
LocalDateTime withMonth(int month) Modify the month dt.withMonth(12)
LocalDateTime withDayOfMonth(int day) Modify the day of the month dt.withDayOfMonth(1)
LocalDateTime withHour(int hour) Modify the hour dt.withHour(0)
LocalDateTime withMinute(int minute) Modify the minute dt.withMinute(0)
LocalDateTime withSecond(int second) Modify the second dt.withSecond(0)
LocalDateTime withNano(int nano) Modify the nanosecond dt.withNano(0)

Date-time comparison

Method Description Example
boolean isAfter(ChronoLocalDateTime other) Whether it is after a specified date-time dt1.isAfter(dt2)
boolean isBefore(ChronoLocalDateTime other) Whether it is before a specified date-time dt1.isBefore(dt2)
boolean isEqual(ChronoLocalDateTime other) Whether it equals a 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 a string dt.format(DateTimeFormatter.ISO_DATE_TIME)
String toString() Convert to an ISO format string "2023-06-15T14:30:45"