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
.
If we use New York-based date-time (UTC -4), we can use “z” pattern-letter for time-zone name: String newYorkDateTimePattern = "dd. MM. yyyy HH:mm z"; DateTimeFormatter newYorkDateFormatter = DateTimeFormatter.
A ZoneId is used to identify the rules used to convert between an Instant and a LocalDateTime . There are two distinct types of ID: Fixed offsets - a fully resolved offset from UTC/Greenwich, that uses the same offset for all local date-times.
Yes, it is: DateTimeFormat is thread-safe and immutable, and the formatters it returns are as well. Implementation Requirements: This class is immutable and thread-safe.
public final class DateTimeFormatter extends Object. Formatter for printing and parsing date-time objects. This class provides the main application entry point for printing and parsing and provides common implementations of DateTimeFormatter : Using predefined constants, such as ISO_LOCAL_DATE.
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With