我需要从这样指定区域的文件中解析时区: UTC、SAST等等。
问题:虽然ZoneId.of("UTC")运行良好,但我不能对SAST做同样的工作。
我得到了java.time.zone.ZoneRulesException: Unknown time-zone ID: SAST。
问题:如何将"SAST“字符串转换为ZoneId
我知道,每次我收到它,我都可以用"GMT+2“代替"SAST”,但是如果有一种更优雅的方法,那就太好了。
发布于 2020-08-03 09:10:35
根据oracle文档的说法,南非标准时间是非洲/约翰内斯堡。所以你应该用:
ZoneId.of("Africa/Johannesburg")发布于 2020-08-03 08:51:37
DisplayZoneAndOffSet.java
package com.mkyong;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.time.ZonedDateTime;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
public class DisplayZoneAndOffSet {
public static final boolean SORT_BY_REGION = false;
public static void main(String[] argv) {
Map<String, String> sortedMap = new LinkedHashMap<>();
Map<String, String> allZoneIdsAndItsOffSet = getAllZoneIdsAndItsOffSet();
//sort map by key
if (SORT_BY_REGION) {
allZoneIdsAndItsOffSet.entrySet().stream()
.sorted(Map.Entry.comparingByKey())
.forEachOrdered(e -> sortedMap.put(e.getKey(), e.getValue()));
} else {
// sort by value, descending order
allZoneIdsAndItsOffSet.entrySet().stream()
.sorted(Map.Entry.<String, String>comparingByValue().reversed())
.forEachOrdered(e -> sortedMap.put(e.getKey(), e.getValue()));
}
// print map
sortedMap.forEach((k, v) ->
{
String out = String.format("%35s (UTC%s) %n", k, v);
System.out.printf(out);
});
System.out.println("\nTotal Zone IDs " + sortedMap.size());
}
private static Map<String, String> getAllZoneIdsAndItsOffSet() {
Map<String, String> result = new HashMap<>();
LocalDateTime localDateTime = LocalDateTime.now();
for (String zoneId : ZoneId.getAvailableZoneIds()) {
ZoneId id = ZoneId.of(zoneId);
// LocalDateTime -> ZonedDateTime
ZonedDateTime zonedDateTime = localDateTime.atZone(id);
// ZonedDateTime -> ZoneOffset
ZoneOffset zoneOffset = zonedDateTime.getOffset();
//replace Z to +00:00
String offset = zoneOffset.getId().replaceAll("Z", "+00:00");
result.put(id.toString(), offset);
}
return result;
}}
https://stackoverflow.com/questions/63226340
复制相似问题