Reputation: 3826
Trying to convert a various of time formats to a unified format.
One format is
"uuuu-MM-dd'T'HH:mm:ss-5000"
need to convert to the timezone format:
"uuuu-MM-dd'T'HH:mm:ss EST"
Using the following code, but it only gives the timezone as "-05:00", but not the expected "EST".
String targetFormat = "uuuu-MM-dd'T'HH:mm:ss z";
String origFormat = "uuuu-MM-dd'T'HH:mm:ss.SSSZ";
String origStr = "2018-02-05T17:25:18.156-0500";
ZonedDateTime time = ZonedDateTime.parse(origStr, DateTimeFormatter.ofPattern(origFormat));
String targetStr = time.format(DateTimeFormatter.ofPattern(targetFormat));
Output from the above is:
2018-02-05T17:25:18 -05:00
How to get the expected:
2018-02-05T17:25:18 EST
Upvotes: 3
Views: 1380
Reputation: 48
-05:00
is not actually a timezone. It's just an offset: a difference of 5 hours behind UTC, and you can't really map it to a single timezone.
At the date you're using (Feb 2nd 2018), there are 47 timezones using -05:00
*, including areas outside US - and lots of them don't call their timezones "EST", such as Lima, that uses "PET" (Peru Time) or Bogota, that uses "COT" (Colombia Time). Regardless of the names used in each place, they're all using -05:00
at the date and time you're using.
Anyway, when you parse an offset such as -05:00
, the API can't know what timezone you are referring to, because of the reasons listed above (there's more than one and the API itself can't decide it). You must arbitraryly choose a timezone, and then you convert your parsed ZonedDateTime
to that zone:
....
ZonedDateTime time = ZonedDateTime.parse(origStr, DateTimeFormatter.ofPattern(origFormat));
// convert to some arbitrary timezone
time = time.withZoneSameInstant(ZoneId.of("America/New_York"));
I choose "America/New_York" because it's one that uses "EST" in Feb 2018. With that, your targetStr
will be:
2018-02-05T17:25:18 EST
Change the timezone name to the one you want. Note that for dates in June, when Daylight Saving Time is in effect in New York, it'll return "EDT".
*: I'm using JDK 8 with 2018e TZ data files, so this number might differ in your environment.
Upvotes: 3