且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

查找系统时区是在Java中的UTC之前还是之后

更新时间:2023-10-31 14:44:46

您可以比较编号.区域偏移的秒数,例如

You can compare the no. of seconds by which a zone is offset e.g.

import java.time.Instant;
import java.time.ZoneOffset;

public class Main {
    public static void main(String[] args) {
        long offsetSecondsMyTZ = ZoneOffset.systemDefault().getRules().getOffset(Instant.now()).getTotalSeconds();
        if (offsetSecondsMyTZ > 0) {
            System.out.println("My timezone is ahead of UTC");
        } else if (offsetSecondsMyTZ < 0) {
            System.out.println("My timezone is behind UTC");
        } else {
            System.out.println("My timezone is UTC");
        }

        // Assuming my time-zone is UTC
        offsetSecondsMyTZ = ZoneOffset.UTC.getTotalSeconds();
        if (offsetSecondsMyTZ > 0) {
            System.out.println("My timezone is ahead of UTC");
        } else if (offsetSecondsMyTZ < 0) {
            System.out.println("My timezone is behind UTC");
        } else {
            System.out.println("My timezone is UTC");
        }

        // Assuming my time-zone is UTC - 2 hours
        offsetSecondsMyTZ = ZoneOffset.ofHours(-2).getTotalSeconds();
        if (offsetSecondsMyTZ > 0) {
            System.out.println("My timezone is ahead of UTC");
        } else if (offsetSecondsMyTZ < 0) {
            System.out.println("My timezone is behind UTC");
        } else {
            System.out.println("My timezone is UTC");
        }
    }
}

输出:

My timezone is ahead of UTC
My timezone is UTC
My timezone is behind UTC

注意::该解决方案基于此答案.