Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert Date to ZonedDateTime?

Tags:

java

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.

like image 420
yiwei Avatar asked Aug 20 '15 20:08

yiwei


People also ask

How do I convert a date object to zoneddatetime?

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.

How to convert localdate to zoneddatetime in Laravel?

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.

How to get a zoneddatetime from a string in Java?

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.

How to create a zoneddatetime with a time zone of UTC?

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


1 Answers

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.

like image 87
Andreas Avatar answered Oct 09 '22 01:10

Andreas