查找系统时区是在Java中的UTC之前还是之后 [英] Find if system timezone is ahead or behind UTC in java

查看:99
本文介绍了查找系统时区是在Java中的UTC之前还是之后的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要确定我当前的系统时区是UTC时区之前还是之后,我尝试了不同的方法,但是问题是我想从系统中获取当前时区并将其与UTC进行比较.

I need to find out if my current system timezone is ahead or behind UTC timezone, I have tried different ways but the problem is I want to fetch the current time zone from the system and compare it with UTC.

有很多与此相关的问题,但是对于概念的前后,我没有发现任何问题.

There are many questions related to this but for ahead and behind concept I didn't find any.

我没有问如何找到zoneOffset.我只想检查应用程序是在UTC时区之前还是在UTC时区之后.

I am not asking how to find zoneOffset. I just wanted to check if the application is ahead or behind UTC timezone.

推荐答案

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

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

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

这篇关于查找系统时区是在Java中的UTC之前还是之后的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆