-1

I have stored in a String type variable my_date a value retrieved from an XML file.

The my_date is in GMT and has a timezone offset that needs to be considered for the UTC conersion.

I would like to convert it (another String) but in UTC format without the timezone - for example:

String my_date = "2020-02-16T20:40:55.000+01:00"
//Convertion
String my_date_utc = "2020-02-16 21:40:55.000"
double-beep
  • 5,031
  • 17
  • 33
  • 41
Alg_D
  • 2,242
  • 6
  • 31
  • 63

1 Answers1

2

Parse as a OffsetDateTime object. Adjust the offset to UTC, producing a second OffsetDateTime object.

OffsetDateTime
.parse
(
    "2020-02-16T20:40:55.000+01:00"
)
.withOffsetSameInstant
(
    ZoneOffset.UTC
)

Understand that date-time objects are not String objects. They parse and generate strings as inputs and outputs.

Search Stack Overflow to learn about producing strings in various formats using DateTimeFormatter. That has been covered many hundreds of times already.

Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
  • [`OffsetDateTime`](https://docs.oracle.com/javase/8/docs/api/java/time/OffsetDateTime.html) doesn't have a `withOffset()` method, so you should change that to [`withOffsetSameInstant()`](https://docs.oracle.com/javase/8/docs/api/java/time/OffsetDateTime.html#withOffsetSameInstant-java.time.ZoneOffset-), and since the desired result is without time zone, you should call [`toLocalDateTime()`](https://docs.oracle.com/javase/8/docs/api/java/time/OffsetDateTime.html#toLocalDateTime--) after that, rather than rely on the formatter to not output the time zone. – Andreas Mar 01 '20 at 16:15
  • @Andreas (A) Thanks for the correction on my error with method name. Now fixed. (B) I disagree about using `LocalDateTime`. Stripping away vital context information (the offset) simply for reporting where that context can be assumed by the person reading is needlessly extreme. Reporting a value to the user as text is a job separate from managing that value internally. That reporting job is exactly the purpose of `DateTimeFormatter`. – Basil Bourque Mar 01 '20 at 16:25