如何在Java中从给定的ZoneOffset中获取ZoneId值



我正试图通过给定区域偏移量来获得所有的区域Id,例如"GMT+2";作为字符串。但是,我不确定是否可以使用任何Java 8+库。是否可以获得具有给定区域偏移的所有区域id值?

java.time中有一个名为getAvailableZoneId()的方法,但它不使用偏移量参数。

如果您想要当前与UTC的偏移量为+02:00小时的区域,您可以尝试通过getAvailableZoneIds()getRules()getOffset(Instant instant)进行过滤来收集区域名称(而不是直接收集ZoneId对象)。后者需要一个参数来定义此方法所基于的时刻。
在本例中,现在是Instant.now():

public static void main(String[] args) throws Exception {
// define the desired offset
ZoneOffset plusTwo = ZoneOffset.ofHours(2);
// collect all the zones that have this offset at the moment
List<String> zonesWithPlusTwo = 
ZoneId.getAvailableZoneIds()
.stream()
// filter by those that currently have the given offset
.filter(zoneId -> ZoneId.of(zoneId)
.getRules()
.getOffset(Instant.now())
.equals(plusTwo))
.sorted()
.collect(Collectors.toList());
// print the collected zones
zonesWithPlusTwo.forEach(System.out::println);
}

今天,2021年8月25日,产量为

Africa/Blantyre
Africa/Bujumbura
Africa/Cairo
Africa/Ceuta
Africa/Gaborone
Africa/Harare
Africa/Johannesburg
Africa/Khartoum
Africa/Kigali
Africa/Lubumbashi
Africa/Lusaka
Africa/Maputo
Africa/Maseru
Africa/Mbabane
Africa/Tripoli
Africa/Windhoek
Antarctica/Troll
Arctic/Longyearbyen
Atlantic/Jan_Mayen
CET
Egypt
Etc/GMT-2
Europe/Amsterdam
Europe/Andorra
Europe/Belgrade
Europe/Berlin
Europe/Bratislava
Europe/Brussels
Europe/Budapest
Europe/Busingen
Europe/Copenhagen
Europe/Gibraltar
Europe/Kaliningrad
Europe/Ljubljana
Europe/Luxembourg
Europe/Madrid
Europe/Malta
Europe/Monaco
Europe/Oslo
Europe/Paris
Europe/Podgorica
Europe/Prague
Europe/Rome
Europe/San_Marino
Europe/Sarajevo
Europe/Skopje
Europe/Stockholm
Europe/Tirane
Europe/Vaduz
Europe/Vatican
Europe/Vienna
Europe/Warsaw
Europe/Zagreb
Europe/Zurich
Libya
MET
Poland

EDIT:考虑到@BasilBorque的注释,这里有一个示例方法,它采用两个参数,一个偏移值和一个Instant作为计算的基础:

public static List<String> getZones(int offsetHours, Instant base) {
// create the offset
ZoneOffset offset = ZoneOffset.ofHours(offsetHours);
// collect all the zones that have this offset at the moment 
return ZoneId.getAvailableZoneIds()
.stream()
// filter by those that currently have the given offset
.filter(zoneId -> ZoneId.of(zoneId)
.getRules()
.getOffset(base)
.equals(offset))
.sorted()
.collect(Collectors.toList());
}

您可以创建一个局部变量(可能是类成员),以便将其传递给方法。这将减少对Instant.now()的调用量,并使您能够使用与调用该方法时不同的Instant

最新更新