繁体   English   中英

如何从时区偏移

[英]How to get offset from TimeZone

我只是想从 TimeZone 获得 offset(+02:00) 但似乎它不适用于 IST、JST、EST 和 BET。

TimeZone exchangeTimeZone = banker.getTimeZone();   
String timeZone = ZonedDateTime.now(ZoneId.of(exchangeTimeZone.getID())).getOffset().getId();

它返回错误“未知时区 ID:EST”。 我无法使用日期对象。

使用ZoneId.SHORT_IDS

ZonedDateTime.now(ZoneId.of(exchangeTimeZone.getID(), ZoneId.SHORT_IDS))
             .getOffset().getId();

您可以尝试为您得到的缩写查找映射:

public static ZoneId getFromAbbreviation(String abbreviation) {
    return ZoneId.of(ZoneId.SHORT_IDS.get(abbreviation));
}

你可以得到像这个main的偏移量:

public static void main(String[] args) {
    ZoneId istEquivalent = getFromAbbreviation("IST");
    ZoneId estEquivalent = getFromAbbreviation("EST");
    ZoneId jstEquivalent = getFromAbbreviation("JST");
    ZoneId betEquivalent = getFromAbbreviation("BET");
    ZonedDateTime istNow = ZonedDateTime.now(istEquivalent);
    ZonedDateTime estNow = ZonedDateTime.now(estEquivalent);
    ZonedDateTime jstNow = ZonedDateTime.now(jstEquivalent);
    ZonedDateTime betNow = ZonedDateTime.now(betEquivalent);
    System.out.println("IST --> " + istEquivalent + " with offset " + istNow.getOffset());
    System.out.println("EST --> " + estEquivalent + " with offset " + estNow.getOffset());
    System.out.println("JST --> " + jstEquivalent + " with offset " + jstNow.getOffset());
    System.out.println("BET --> " + betEquivalent + " with offset " + betNow.getOffset());
}

输出是

IST --> Asia/Kolkata with offset +05:30
EST --> -05:00 with offset -05:00
JST --> Asia/Tokyo with offset +09:00
BET --> America/Sao_Paulo with offset -03:00

如您所见, EST没有区域名称,只有一个偏移量。

TimeZone.toZoneId()

    // Never do this in your code: Get a TimeZone with ID EST for demonstration only.
    TimeZone tz = TimeZone.getTimeZone("EST");
    
    String currentOffsetString = ZonedDateTime.now(tz.toZoneId())
            .getOffset()
            .getId();
    System.out.println(currentOffsetString);

刚才运行时的输出:

-05:00

与您在代码中使用的单参数ZoneId.of方法相反, TimeZone.toZoneId()确实处理不推荐使用的三个字母缩写(根据您的情况和喜好,这可能被视为优势或劣势)。 所以上面的代码也适用于许多这样的三字母缩写,包括 EST。

我只是犹豫地包括上面的第一行代码。 它有几个问题:我们不应该在我们的代码中创建老式的TimeZone对象,而应该依赖现代ZonedId和来自 java.time 的相关类,现代 Java 日期和时间 API。 我们也不应该依赖三个字母的时区缩写。 它们已被弃用,未标准化且通常含糊不清。 例如,EST 可能表示澳大利亚东部标准时间或北美东部标准时间。 为了增加混淆,有些人会期望您在夏季使用夏令时 (DST) 获得东部时间。 使用TimeZone则不会。 您将获得一个全年使用标准时间的时区。 对于 AST、PST 或 CST,情况并非如此。

但是,您通常无法控制从 API 获得的内容。 如果你不幸得到一个 ID 为 EST 的老式TimeZone对象,上面的代码向你展示了进入 java.time 领域所需的转换。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM