I've got various java.util.Date
objects with values of this format: 2014-01-21 10:28:57.122Z
. I would like to convert them all to ZonedDateTime
objects.
According to this SO question, and ZonedDateTime
's ofInstant()
, one way is like so:
ZonedDateTime z = ZonedDateTime.ofInstant(dateObject.toInstant(), ZoneId);
The problem is, how do I figure out what to use for the ZoneId
parameter? I can't use my system time (ZoneId.systemDefault()
) because my Date
objects all have different timezones.
When you display a Date object, the formatter will generate the text as requested, in the time zone requested, whether the time zone is displayed or not. So, without time zone information in the Date object, you must specify the time zone you want when converting to ZonedDateTime.
To convert the LocalDate to ZonedDateTime, we must add the time and zone id with the local date. In this example, we have date in the string format, we are first parsing the given date in LocalDate and then converting the LocalDate to ZonedDateTime using the atStartOfDay() method.
A second option to obtain a ZonedDateTime from a String involves 2 steps: converting the String to a LocalDateTime, then this object to a ZonedDateTime: This indirect method simply combines the date-time with a zone id: To learn more about parsing String to dates, check out our more in-depth date parsing article.
First, we’ll start with a ZonedDateTime with a time zone of UTC. There are several ways we can accomplish this. We can specify the year, month, day, etc: We can also create a ZonedDateTime from the current date and time: Or, we can create a ZonedDateTime from an existing LocalDateTime: 3. ZonedDateTime to String
Your java.util.Date
object does not have a time zone. Dates are always stored internally in UTC.
When you parse a text string into a Date
object, the parser applies a time zone, either as given in the text, as a parameter to the parser, or by default.
When you display a Date
object, the formatter will generate the text as requested, in the time zone requested, whether the time zone is displayed or not.
So, without time zone information in the Date
object, you must specify the time zone you want when converting to ZonedDateTime
.
Better yet, parse the text directly to a ZonedDateTime, so it can remember the original time zone from the text.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With