Java, Software Development

Java – Convert LocalDateTime to OffsetDateTime in any timezone

This post shows how to convert a Java LocalDateTime object to an OffsetDateTime object at the current zone offset. For example, let’s say we are in Singapore and want to convert the current LocalDateTime to a string value. This string value will contain the date/time information plus the offset.

Convert To OffsetDateTime Using Zone Offset

Basically, we want to append a LocalDateTime object with the current zone offset without converting it first to a string object (to concatenate it with +/-##:##) and then to an OffsetDateTime object. We just want the zone offset based on where we execute the codes.

LocalDateTime To OffsetDateTime Codes

Consider the following codes. First, we create a LocalDateTime object. Then, we get our offset using OffsetDateTime on the current date and time. As a result, we get a string value representing our current offset. In our case, the offset is +8.

Next, we use the offset to convert the Java LocalDateTime object to an OffsetDateTime object by using the atOffset method. With this technique, we can avoid string concatenation and let the appropriate objects do the conversion work.

Testing

When we run the Java codes we have, we get the following output.

What if we only use OffsetDateTime.now() instead with Java LocalDateTime object? We could do that. However, the resulting string may require manipulation depending on our needs. Consider the following codes and the output.

Unless we need to capture the time accurately, we still need to manipulate the string value to extract the date/time only up to the minute. Alternatively, we could use a DateTimeFormatter instance with just an instance of OffsetDateTime. Meaning, we do not use a Java LocalDateTime object at all. Consider the following codes.

The codes generate the following output.

For more information on the pattern, please see OffsetDateTime’s toString method documentation. We could use any of the following ISO-8601 formats for reference.

This post is (now) part of a reboot Java tutorial.

Got comments or suggestions? We disabled the comments on this site to fight off spammers, but you can still contact us via our Facebook page!.


You Might Also Like