2016-02-28 104 views
2

我使用Java 8
这是我ZonedDateTime看起来像ZonedDateTime到UTC并应用偏移量?

2013-07-10T02:52:49+12:00 

我得到这个值作为

z1.format(DateTimeFormatter.ISO_OFFSET_DATE_TIME) 

其中z1ZonedDateTime

我想这个值作为2013-07-10T14:52:49

我怎么能这样做转换?

+1

我还是不明白:d。它与http://stackoverflow.com/q/35688559/1743880有何不同? “convert to'2013-07-10T14:52:49'”是什么意思? – Tunaki

+0

将'+12小时'应用于'02:52:49'以使它成为'14:52:59',现在清楚了吗? – daydreamer

+1

所以你想在未来的12小时内为同一区域偏移? – Tunaki

回答

3

这是你想要的吗? 这会将您的ZonedDateTime转换为LocalDateTime,给定的ZoneIdZonedDateTime转换为Instant

LocalDateTime localDateTime = LocalDateTime.ofInstant(z1.toInstant(), ZoneId.of("UTC")); 

或者,也许你希望用户系统时区,而不是硬编码UTC:

LocalDateTime localDateTime = LocalDateTime.ofInstant(z1.toInstant(), ZoneId.systemDefault()); 
+0

@assylias:感谢您的编辑,但您可以看到我在说什么:在您的编辑中,LocalDateTime.ofInstant会转换为LocalDateTimeofstant。 – SimMac

+0

呵呵......我看起来很好...你也许可以尝试用不同的浏览器来检查你是否有同样的问题。 – assylias

+0

奇怪的是,它仅适用于OS X的Chrome浏览器(即使在没有插件的情况下也是如此)。 – SimMac

0

@SimMac感谢您的清晰度。我也面临同样的问题,并能根据他的建议找到答案。

public static void main(String[] args) { 
    try { 
     String dateTime = "MM/dd/yyyy HH:mm:ss"; 
     String date = "09/17/2017 20:53:31"; 
     Integer gmtPSTOffset = -8; 
     ZoneOffset offset = ZoneOffset.ofHours(gmtPSTOffset); 

     // String to LocalDateTime 
     LocalDateTime ldt = LocalDateTime.parse(date, DateTimeFormatter.ofPattern(dateTime)); 
     // Set the generated LocalDateTime's TimeZone. In this case I set it to UTC 
     ZonedDateTime ldtUTC = ldt.atZone(ZoneOffset.UTC); 
     System.out.println("UTC time with Timezone   : "+ldtUTC); 

     // Convert above UTC to PST. You can pass ZoneOffset or Zone for 2nd parameter 
     LocalDateTime ldtPST = LocalDateTime.ofInstant(ldtUTC.toInstant(), offset); 
     System.out.println("PST time without offset   : "+ldtPST); 

     // If you want UTC time with timezone 
     ZoneId zoneId = ZoneId.of("America/Los_Angeles"); 
     ZonedDateTime zdtPST = ldtUTC.toLocalDateTime().atZone(zoneId); 
     System.out.println("PST time with Offset and TimeZone : "+zdtPST); 

    } catch (Exception e) { 
    } 
} 

输出:

UTC time with Timezone   : 2017-09-17T20:53:31Z 
PST time without offset   : 2017-09-17T12:53:31 
PST time with Offset and TimeZone : 2017-09-17T20:53:31-08:00[America/Los_Angeles] 
相关问题