1

I am trying to get the current UTC time and convert it into a Date object:

      OffsetDateTime now = OffsetDateTime.now(ZoneOffset.UTC);
      Date date = Date.from(now.toInstant());

The problem I face is that OffsetDateTime returns the correct time, for example 2023-03-22T08:46:38.562331200Z, which is correct in the time of writing, but when converting it to Date object the date becomes Wed Mar 22 10:46:38 EET 2023 with my timezone EET, how can I create a Date object with the UTC time 2023-03-22T08:46:38.562331200Z retrieved?

Ole V.V.
  • 81,772
  • 15
  • 137
  • 161
Joel
  • 85
  • 4
  • 1
    I am trying to convert it to Date so then I can pass it to a query in the database which expect Date object to compare with – Joel Mar 22 '23 at 09:07
  • 1
    I think yes , it returns the correct UTC time – Joel Mar 22 '23 at 09:23
  • Avoid the outdated `Date` class if you can. If you need one for a legacy API, just trust that you have got the right one even though it prints in your local time zone (`Date` objects always did that). – Ole V.V. Mar 22 '23 at 10:46
  • How are you querying the database? Most modern JDBC drivers accept an `OffsetDateTime` as query parameter. See for example [this answer by Arvind Kumar Avinash](https://stackoverflow.com/a/67505173/5772882). As I said, don’t use `Date` if you can avoid it. – Ole V.V. Mar 22 '23 at 10:56
  • *but when converting it to Date object the date becomes Wed Mar 22 10:46:38 EET 2023 with my timezone EET* It doesn't. What you probably mean is this is what is getting printed when you visualize it. That's because your system timezone is being applied to it – g00se Mar 23 '23 at 10:28

0 Answers0