Reputation: 3225
I have this string "Tue Apr 09 2019 12:59:51 GMT+0300"
I want to convert to ZonedDateTime
.
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("EEE MMM dd yyyy HH:mm:ss OOOO");
ZonedDateTime zdt = ZonedDateTime.parse(a, dtf);
After convert to ZonedDateTime
, I want to change the timezone from GMT+0300
to other timezone.
My first problem is at parse
. I get:
DateTimeParseException: Text 'Tue Apr 09 2019 12:59:51 GMT+0300' could not be parsed at index 25
(at GMT+0300, I think OOOO
it's not right, but I don't know what else it is)
After that I don't know how to change the timezone.
Upvotes: 2
Views: 1299
Reputation: 86120
Since your string contains an offset and no time zone, what do you want a ZonedDateTime
for? OffsetDateTime
is more appropriate.
DateTimeFormatter dtf = DateTimeFormatter.ofPattern(
"EEE MMM dd yyyy HH:mm:ss 'GMT'xx", Locale.ROOT);
String a = "Tue Apr 09 2019 12:59:51 GMT+0300";
System.out.println(OffsetDateTime.parse(a, dtf));
2019-04-09T12:59:51+03:00
A time zone is a place on earth and encompasses historic and known future changes in UTC offset in that place. A time zone is conventionally given in the region/city format, for example Asia/Rangoon.
Edit
I use ZonedDateTime because I use time zone in my app.
I’m unsure exactly what you mean. Maybe you have decided in advance which time zone you are using? For example:
ZoneId zone = ZoneId.of("Europe/Zaporozhye");
OffsetDateTime odt = OffsetDateTime.parse(a, dtf);
ZonedDateTime zdt = odt.atZoneSameInstant(zone);
System.out.println(zdt);
2019-04-09T12:59:51+03:00[Europe/Zaporozhye]
If for some reason you want to regard GMT+0300 as a time zone even though it isn’t, the parsing I showed first works with ZonedDateTime
too:
System.out.println(ZonedDateTime.parse(a, dtf));
2019-04-09T12:59:51+03:00
Upvotes: 2
Reputation: 28269
OOOO
expects the a colon before minute field, as the doc says:
Four letters outputs the full form, which is localized offset text, such as 'GMT, with 2-digit hour and minute field, optional second field if non-zero, and colon, for example 'GMT+08:00'.
You can insert a :
before the last 00
programmatically, then parse it.
Upvotes: 4