Reputation: 10995
I have the following DateTimeFormatter
.
DateTimeFormatter DATE_TIME_FORMATTER =
DateTimeFormatter.ofPattern("MM/dd/yyyy 'at' hh:mm:ss a zzzz");
I am using it to format a ZonedDateTime
like this:
ZonedDateTime disableTime = Instant.now()
.plus(Duration.ofDays(21))
.atZone(ZoneId.ofOffset("UTC", ZoneOffset.ofHours(-5)));
System.out.println(DATE_TIME_FORMATTER.format(disableTime));
I would like this to ouput a formatted date string, like the following:
09/16/2015 at 01:15:45 PM EDT
But what is getting output is this:
09/16/2015 at 01:15:45 PM UTC-05:00
No matter whether I use z
, zz
, zzz
, or zzzz
in the pattern, it always gets output in the above format.
Is there a different way to create the ZonedDateTime
that will give me the desired output, or am I doing something wrong in the pattern?
As per the DateTimeFormatter
documentation, O
should be used to display the localized zone-offset, such as UTC-05:00
, while z
should be used to display the time-zone name, such as Eastern Daylight Time
, or EDT
.
Upvotes: 11
Views: 4013
Reputation: 20885
This is because you use an anonymous UTC offset. Try with a named ZoneId
instead
ZonedDateTime disableTime = Instant.now()
.plus(Duration.ofDays(21))
.atZone(ZoneId.of("Africa/Nairobi"));
prints ("Ora dell'Africa orientale" is italian localized names)
09/16/2015 at 09:34:44 PM Ora dell'Africa orientale
You can get a list of available names that should use to store and retrieve the preferences from the user with
Set<String> ids = ZoneId.getAvailableZoneIds();
Upvotes: 7