问题描述
我有一个微调器,可以从中选择所需的时区。当我选择时区时,将显示相关的当前时间。 在微调器中,我希望时区采用以下配置: 例如美国/洛杉矶(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切换到modern java.time
日期时间API。从 Trail: Date Time 了解有关现代日期时间API的更多信息。
如果您的Android API级别仍不兼容Java8,请选中How to use ThreeTenABP in Android Project和Java 8+ APIs available through desugaring。
使用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)