Convert OffsetDateTime to LocalDateTime
1 Comment
Java 8 introduced a new date and time API defined inside
java.time package
. The key date and time classes defined in this package are
LocalDateTime
,
LocalDateTime
, and
OffsetDateTime
.
OffsetDateTime
represents a date-time with an offset. This class stores all date and time fields, to a precision of nanoseconds, as well as the offset from UTC/Greenwich. For example, the value
2nd December 2018
at
15:35.40.123456789 +03:00
can be stored in an
OffsetDateTime
.
On the other hand,
LocalDateTime
represents a date and time without time zone information. An example is
2020-07-12T17:23:10.205580
.
In addition to
LocalDateTime
, you can also use the
LocalDate
and
LocalTime
classes to work with date and time without time-zone separately.
An example of
LocalDate
is
2018-10-05
. An example of
LocalTime
is
15:19:47.459
.
In my previous post, I explained how to convert
OffsetDateTime
to
ZonedDateTime.
In this post, I’ll discuss how to convert
OffsetDateTime
to
LocalDateTime
,
LocalDate
, and
LocalTime
.
Converting OffsetDateTime To LocalDateTime
The code for converting
OffsetDateTime
to
LocalDateTime
is this.
public LocalDateTime convertToLocalDateTime() {
OffsetDateTime offsetDateTime = OffsetDateTime.now();
System.out.println(offsetDateTime);
LocalDateTime localDateTime = offsetDateTime.toLocalDateTime();
System.out.println("localDateTime = " + localDateTime);
return localDateTime;
In the preceding code,
OffsetDateTime.now()
gets the current date-time in the default time-zone with an offset. Then
offsetDateTime.toLocalDateTime()
converts the current date-time
LocalDateTime
.
Let’s call this method from our main class.
DateConverter dateConvertor = new DateConverterImpl(); dateConvertor.convertToLocalDateTime();
On running the application, the output is this.
2020-07-12T18:51:36.240918
Converting OffsetDateTime To LocalDate
At times, you might want only the local date instead of a full date and time with offset. For that, you need to convert the
OffsetDateTime
to
LocalDate.
The code is this.
public LocalDate convertToLocalDate() {
OffsetDateTime offsetDateTime = OffsetDateTime.now();
System.out.println(offsetDateTime);
LocalDate localDate=offsetDateTime.toLocalDate();
System.out.println(localDate);
return localDate;
The output on calling the preceding method is this.
2020-07-12
Converting OffsetDateTime To LocalTime
The
OffsetDateTime
class also allows conversion to local time.
The code for converting
OffsetDateTime
to
LocalTime
is this.
public LocalTime convertToLocalTime() {
OffsetDateTime offsetDateTime = OffsetDateTime.now();
System.out.println(offsetDateTime);