格式化时区显示名称(例如UTC+01:00)



我有一个微调器,可以从中选择所需的时区。当我选择时区时,会显示相关的当前时间。在微调器中,我希望使用此配置中的时区:例如美国/洛杉矶(UTC-07:00(。相反,我看到了以下内容:美国/洛杉矶(UTC-28800000(。这是代码:

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()) + ")";
}

我建议您从过时且错误的java.util日期时间API切换到现代的java.time日期时间API。从跟踪:日期时间了解有关现代日期时间API的更多信息。

如果您的Android API级别仍然不符合Java8,请检查如何在Android项目中使用ThreeTenABP以及通过desugaring提供的Java 8+API。

使用Java现代日期时间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));
}
}

输出:

Thu Sep 03 2020 14:47:11 America/Los_Angeles (UTC-07:00)

相关内容

最新更新