【问题标题】:How to get local date time for timezone如何获取时区的本地日期时间
【发布时间】:2015-09-23 04:06:56
【问题描述】:

问题来了

我从 API 获取数据为

curl "http://api.timezonedb.com/?lat=53.7833&lng=-1.75&key=OXFVZEHUDERF&format=json"
{"status":"OK","message":"","countryCode":"GB","zoneName":"Europe\/London","abbreviation":"BST","gmtOffset":"3600","dst":"1","timestamp":1442983759}Harits-MacBook-Pro-2:~ harit$ curl "http://api.timezonedb.com/?lat=-44.490947&lng=171.220966&key=API_KEY&format=json"

结果为

{"status":"OK","message":"","countryCode":"NZ","zoneName":"Pacific\/Auckland","abbreviation":"NZST","gmtOffset":"43200","dst":"0","timestamp":1443023417}

根据他们的docstimestamp

Unix 时间戳中的当前本地时间。

如何打印成

2013-07-10T14:52:49

在那个时区Europe/London

【问题讨论】:

    标签: java date time


    【解决方案1】:

    虽然你没有提到,但你可以在 java 8 中实现它:

    public static void main(String[] args) throws IOException {
        final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        final long unixTime = 1443023417;
        final String formattedDtm = Instant.ofEpochSecond(unixTime).atZone(ZoneId.of("PLT")).format(formatter);
        System.out.println(formattedDtm);   
        }
    

    它打印: 2015-09-23 11:50:17

    Java 8 引入了 Instant.ofEpochSecond 方法,用于从 Unix 时间戳创建 Instant,然后可以将其转换为 ZonedDateTime,然后可以根据您的要求进行格式化。

    【讨论】:

      【解决方案2】:

      由于您有时区以及时间戳,您可以将 LocalDateTime 获取为

      LocalDateTime lt = LocalDateTime.ofInstant(Instant.ofEpochMilli(timestamp), ZoneId.of(ZoneId.SHORT_IDS.get("BST")));
      System.out.println(lt);
      

      【讨论】:

        猜你喜欢
        • 2014-02-22
        • 2015-08-16
        • 1970-01-01
        • 1970-01-01
        • 2013-07-12
        • 1970-01-01
        • 2021-03-21
        • 2013-06-10
        • 2010-11-09
        相关资源
        最近更新 更多