2016-02-28 76 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] 
相關問題