有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何获取时区偏移量

我只是想从时区获得偏移量(+02:00),但似乎它不适用于IST、JST、EST和BET

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

返回错误“未知时区ID:EST”。日期对象不适用于我


共 (3) 个答案

  1. # 1 楼答案

    使用ZoneId.SHORT_IDS

    ZonedDateTime.now(ZoneId.of(exchangeTimeZone.getID(), ZoneId.SHORT_IDS))
                 .getOffset().getId();
    
  2. # 2 楼答案

    你可以尝试为你得到的缩写找到一个映射:

    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没有区域名称,只有偏移量

  3. # 3 楼答案

    时区。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

    与您在代码中使用的一个argZoneId.of方法相反,TimeZone.toZoneId()确实处理不推荐使用的三个字母缩写(这可能被视为优势或劣势,取决于您的情况和品味)。因此,上述代码也适用于许多这样的三字母缩写,包括EST

    我只是在犹豫是否包含上面的第一行代码。它有几个问题:我们不应该在代码中创建老式的TimeZone对象,而应该依赖java中的现代ZonedId和相关类。时间,现代Java日期和时间API。我们也不应该依赖三个字母的时区缩写。它们被弃用,没有标准化,通常模棱两可。例如,EST可能意味着澳大利亚东部标准时间或北美东部标准时间。为了增加混乱,有些人会希望你在夏天得到东部时间和夏季时间(DST)。有了TimeZone你就没有了。你得到了一个全年都使用标准时间的时区。AST、PST和CST的情况也是如此

    然而,您通常无法控制从API中获得什么。如果你不幸得到了一个ID为EST的老式TimeZone对象,上面的代码将向你展示进入java领域所需的转换。时间到了