1

I have a spinner from which I can choose the desired time zone. When I select a time zone, the related current time is displayed. In the spinner, I would like to have the time zones in this configuration: e.g. America/Los_Angeles (UTC-07:00). Instead, I see the following: America/Los_Angeles (UTC-28800000). This is the code:

String[]TZ = TimeZone.getAvailableIDs();
String NameAndUTC ="";
for(int i = 0; i < TZ.length; i++)
{    
NameAndUTC = TimeZone.getTimeZone(TZ[i]).getID() + " (UTC" + 
             (TimeZone.getTimeZone(TZ[i]).getRawOffset() == 0 ? "+00:00" : 
             TimeZone.getTimeZone(TZ[i]).getRawOffset()) + ")";
}
Francesca
  • 21
  • 3

1 Answers1

2

I recommend you switch from the outdated and error-prone java.util date-time API to the modern java.time date-time API. Learn more about the modern date-time API from Trail: Date Time.

If your Android API level is still not compliant with Java8, check How to use ThreeTenABP in Android Project and Java 8+ APIs available through desugaring.

Do it as follows using the Java modern date-time API:

import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;

public class Main {
    public static void main(String[] args) {
        // Get the set of all time zone IDs.
        Set<String> allZones = ZoneId.getAvailableZoneIds();

        // Create a List using the set of zones and sort it. Now, you can display the
        // sorted list in the spinner
        List<String> zoneList = new ArrayList<String>(allZones);
        Collections.sort(zoneList);

        // Select a value from the spinner e.g.
        String s = "America/Los_Angeles";

        // Get the Zone Id using the selected value from the spinner
        ZoneId zone = ZoneId.of(s);

        // Date and time at the zone selected from the spinner
        ZonedDateTime zdt = ZonedDateTime.now(zone);

        // Define a formatter as per your display requirement e.g.
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("EEE MMM dd yyyy HH:mm:ss VV '(UTC'XXX')'");

        // Display the date time
        System.out.println(zdt.format(formatter));
    }
}

Output:

Thu Sep 03 2020 14:47:11 America/Los_Angeles (UTC-07:00)
Arvind Kumar Avinash
  • 71,965
  • 6
  • 74
  • 110