Java LocalDateTime
Jakob Jenkov |
The LocalDateTime
class in the Java 8 date time API (java.time.LocalDateTime
) represents
a local date and time without any time zone information. You could view the LocalDateTime
as a
combination of the LocalDate
and
LocalTime
classes of the Java 8 date time API.
The LocalDateTime
is immutable, so all methods that perform calculations on the LocalDateTime
return a new LocalDateTime
instance.
Creating a LocalDateTime
You create a LocalDateTime
object via one of its static factory methods. Here is an example that
shows how to create a LocalDateTime
object via the now()
method:
LocalDateTime localDateTime = LocalDateTime.now();
Another way to create a LocalDateTime
object is to create it based on a specific year, month, day etc.
Here is an example of that:
LocalDateTime localDateTime2 = LocalDateTime.of(2015, 11, 26, 13, 55, 36, 123);
The parameters to the of()
method are year, month, day (of month), hours, minutes, seconds
and nanoseconds.
Accessing the Time of a LocalDateTime
You can access the date and time fields of the LocalDateTime
using some of these methods:
getYear()
getMonth()
getDayOfMonth()
getDayOfWeek()
getDayOfYear()
getHour()
getMinute()
getSecond()
getNano()
Some of these methods return an int
and some of them return an enum
. Via the methods that
return an enum
you can get an int
representation of the enum
by calling the
getValue()
of the enum
.
Date Time Calculations
You can perform various date time calculations on the LocalDateTime
object using some of these methods:
plusYears()
plusMonths()
plusDays()
plusHours()
plusMinutes()
plusSeconds()
plusNanos()
minusYears()
minusMonths()
minusDays()
minusHours()
minusMinutes()
minusSeconds()
minusNanos()
Here are a few examples to illustrate how these calculation methods work:
LocalDateTime localDateTime = LocalDateTime.now(); LocalDateTime localDateTime1 = localDateTime.plusYears(3); LocalDateTime localDateTime2 = localDateTime.minusYears(3);
The first line creates a LocalDateTime
instance representing the moment of now. The second line
creates a LocalDateTime
object that represents a date and time 3 years later. The third line creates
a LocalDateTime
object that represents a date and time 3 years earlier.
Tweet | |
Jakob Jenkov |