将UTC时间戳转换为本地日期

时间:2016-07-08 13:47:45

标签: java datetime utc

所以我现在尝试将时间戳转换为本地日期(CEST)大约几个小时。

     Date date = new Date(stamp*1000);
     SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
     simpleDateFormat.setTimeZone(TimeZone.getTimeZone("CEST"));
     String myDate = simpleDateFormat.format(date);

无论我尝试什么,在互联网上查找都没有用,我总是回到UTC时间......

为了更好地理解:stamp是一个类型为long的可变时间戳,我将从服务

接收

2 个答案:

答案 0 :(得分:2)

TL;博士

String output = ZonedDateTime.ofInstant ( Instant.ofEpochSecond ( 1_468_015_200L ) , ZoneId.of ( "Europe/Paris" ) ).toString();

详细

一些问题:

  • 您没有使用proper time zone names
    • 正确的名称采用continent/region格式。
    • 媒体中常见的3-4个字母缩写,如CEST不是真正的时区。 避免使用它们。它们既不是标准化也不是唯一的(!)。
  • 您正在使用设计糟糕且令人困惑的过时的日期时间类。它们已被java.time框架取代。

如果CEST你的意思是夏天提前2小时,那么我们以Europe/Paris为例说明时区。你的问题缺乏示例数据,所以我将编写这个例子。

显然,您输入的是UTC中1970年第一时刻的整秒数。该值可以直接使用,无需乘法。

ZoneId类代表时区。 Instant是UTC时间轴上的一个点,分辨率高达纳秒。 ZonedDateTime Instant调整为ZoneId

ZoneId zoneId = ZoneId.of ( "Europe/Paris" );
long input = 1_468_015_200L;   // Whole seconds since start of 1970.
Instant instant = Instant.ofEpochSecond ( input );
ZonedDateTime zdt = ZonedDateTime.ofInstant ( instant , zoneId );

转储到控制台。

System.out.println ( "input: " + input + " | instant: " + instant + " | zdt: " + zdt );
  

输入:1468015200 |时刻:2016-07-08T22:00:00Z | zdt:2016-07-09T00:00 + 02:00 [欧洲/巴黎]

答案 1 :(得分:0)

您的TimeZone ID可能不正确(嗯,Java无法识别)。在这种情况下,似乎TimeZone被评估为 UTC 而不是抛出异常。

请改为尝试:

simpleDateFormat.setTimeZone(TimeZone.getTimeZone("ECT"));

Here是一个页面,提供有关Java TimeZone的一些信息以及时区ID列表。