在Java中的不同时区和不同的DST之间转换Unix时间戳 [英] Convert unix timestamp between different timezones and different DST in Java

查看:232
本文介绍了在Java中的不同时区和不同的DST之间转换Unix时间戳的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

已解决的问题外部设备正在计算并发送非标准的2小时轮班时间戳,这使我非常困惑,并启动了该线程. 自己的时间戳不受时区的影响,时区仅在以人类可读形式进行转换时适用.

PROBLEM SOLVED External device was computing and sending non-standard 2 hours shifted timestamp, which hugely confused me and started this thread. TIMESTAMP BY ITSELF IS NOT AFFECTED BY TIMEZONES , timezones apply only when converting in/from human readable forms.

我在UTC时区有时间戳记(距Unix纪元的秒数​​),没有DST(夏令时).

I have timestamp (seconds from unix epoch) in UTC timezone - no DST (daylight saving time).

我想要使用DST的欧洲/布拉格"时区的时间戳记(距unix纪元的秒数​​).

I want timestamp (seconds from unix epoch) in "Europe/Prague" timezone, that uses DST.

我曾经认为unix时间戳不受时区的限制,时区仅影响将时间戳转换为人类可读格式的过程.但这看起来不是那样.而且,我尝试转换的次数越多(使用Calendar和TimeZone类),我就会变得越来越困惑和迷茫.

I used to think that unix timestamp is unbound by timezones, that timezones affect only process of converting timestamp to human readable formats. But it doesn't look like that. And the more I am trying to convert it (using Calendar and TimeZone classes), the more confused and lost I am getting.

此代码无法正常工作:

Calendar cal = GregorianCalendar.getInstance(TimeZone.getTimeZone("UTC"));
cal.setTimeInMillis(ts*1000);
cal.setTimeZone(TimeZone.getTimeZone("Europe/Prague"));
return cal.getTimeInMillis()/1000;

推荐答案

没有一种方法可以转换"时间戳,它始终是从纪元开始的毫秒数.

There is not a way to "convert" a timestamp, it is always the number of milliseconds from the epoch.

您可以使用DateFormat将时间戳格式化为应用了时区的格式,也可以使用日历查看应用了时区的小时,分​​钟和秒.

You can use a DateFormat to format the timestamp into a format with a time zone applied, or use a Calendar to look at the hours, minutes, and seconds with a time zone applied.

getTimeInMillis()返回的时间戳与您输入的时间戳相同,即从纪元开始的毫秒数: http://docs .oracle.com/javase/1.5.0/docs/api/java/util/Calendar.html#getTimeInMillis%28%29

getTimeInMillis() gets the timestamp back just the same as you put it in, the number of milliseconds from the epoch: http://docs.oracle.com/javase/1.5.0/docs/api/java/util/Calendar.html#getTimeInMillis%28%29

这篇关于在Java中的不同时区和不同的DST之间转换Unix时间戳的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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