Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Display short time zone name using DateTimeFormatter

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.

like image 747
Andrew Mairose Avatar asked Aug 26 '15 18:08

Andrew Mairose


People also ask

How do I change the TimeZone in DateTimeFormatter?

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.

What is ZoneId of UTC?

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.

Is DateTimeFormatter thread safe?

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.

What is DateTimeFormatter?

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.


1 Answers

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();
like image 97
Raffaele Avatar answered Oct 18 '22 22:10

Raffaele