如何从时间戳值获取时区 ID

Moh*_*nFM 0 java time timestamp date

是否可以从某个 TimeStamp 获取 TimeZone ID?如果是,请用简单的代码解释一下。

 private String getDate(long timeStamp) {DateFormat objFormatter = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
    TimeZone timeZone = TimeZone.getTimeZone("GMT+4:30");
    //Instead of the Above code I want to get the TimeZone ID from my timeStamp objFormatter.setTimeZone(timeZone);
    Calendar objCalendar =
            Calendar.getInstance(timeZone);
    objCalendar.setTimeInMillis(timeStamp * 1000);
    String result = objFormatter.format(objCalendar.getTime());
    objCalendar.clear();
    return result;
}
Run Code Online (Sandbox Code Playgroud)

Bas*_*que 6

tl;博士

不可能从 UTC 中的纪元计数派生偏移量/区域。但是你可以调整一个区域。

Instant.ofEpochSecond( yourCount )
       .atZone( ZoneId.of( "Pacific/Auckland" ) ) 
Run Code Online (Sandbox Code Playgroud)

避免从纪元开始计数

首先,避免使用从纪元计数来跟踪日期时间值。你的意思是整秒、毫秒、微秒、纳秒或其他什么的计数?你的意思是在Unix / Java的划时代1970-01-01T00:00:00Z或一对夫妇打其他时期使用的许多计算机系统?

显然你有整整几秒钟,我会假设 Unix/Java 时代。

不可能从纪元计数中获得区域

您不能“从某个时间戳中获取时区 ID”,这是不可能的。您的 epoch 计数是在考虑某个时区时进行的,通常是UTC。如果必须知道用于创建该纪元计数的预期区域,则无法推断出它。

也许您的目标实际上是将这个从纪元计数调整为特定地区时区的日期时间。继续阅读。

时间

避免麻烦的旧日期时间类,例如Date&Calendar现在被 java.time 类取代。

将您的纪元计数转换为 UTC 时间线上的一个点。

Instant instant = Instant.ofEpochSecond( yourCount ) ;
Run Code Online (Sandbox Code Playgroud)

分配您想要的时区。

以、、 或等格式指定正确的时区名称。永远不要使用 3-4 个字母的缩写,例如或因为它们不是真正的时区,不是标准化的,甚至不是唯一的(!)。continent/regionAmerica/MontrealAfrica/CasablancaPacific/AucklandESTIST

ZoneId z = ZoneId.of( "Asia/Kabul" ) ;
ZonedDateTime zdt = instant.atZone( z ) ;
Run Code Online (Sandbox Code Playgroud)

查看此代码在 IdeOne.com 上实时运行

请注意 4.5 小时的差异,从 02:40 更改为 07:10,适用于喀布尔的时间。这是同一时刻,时区上的同一点,但通过不同地区挂钟时间的镜头来看。

输入:1500000000

即时:2017-07-14T02:40:00Z

zdt: 2017-07-14T07:10+04:30[亚洲/喀布尔]