Java: Calculating time zone difference

后端 未结 5 819
野的像风
野的像风 2021-02-07 19:07

How do I get the time difference from GMT for a specific date and time zone in Java?

Determining whether a specific time zone is in DST is quite straight-forward:

<
5条回答
  •  暖寄归人
    2021-02-07 19:26

    public String timeZone(Date date) {
        TimeZone timeZone = TimeZone.getTimeZone("America/New_York");
        long millis = timeZone.getRawOffset() + (timeZone.inDaylightTime(date) ? timeZone.getDSTSavings() : 0);
    
        return String.format("%s%s:%s",
                millis < 0 ? "-" : "+",
                String.format("%02d", Math.abs(TimeUnit.MILLISECONDS.toHours(millis))),
                String.format("%02d", Math.abs(TimeUnit.MILLISECONDS.toMinutes(millis) - TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(millis))))
        );
    }
    

提交回复
热议问题