2017-10-18 395 views
-2

我想用DateTimeFormatter.ISO_LOCAL_DATE來打印和解析日期。這是我在做什麼印刷:如何使用DateTimeFormatter.ISO_LOCAL_DATE打印日期?

Date date; 
String text = DateTimeFormatter.ISO_LOCAL_DATE.format(
    date.toInstant() 
); 

這就是我得到:

java.time.temporal.UnsupportedTemporalTypeException: Unsupported field: Year 
    at java.time.Instant.getLong(Instant.java:603) 
    at java.time.format.DateTimePrintContext$1.getLong(DateTimePrintContext.java:205) 
    at java.time.format.DateTimePrintContext.getValue(DateTimePrintContext.java:298) 
    at java.time.format.DateTimeFormatterBuilder$NumberPrinterParser.format(DateTimeFormatterBuilder.java:2543) 
    at java.time.format.DateTimeFormatterBuilder$CompositePrinterParser.format(DateTimeFormatterBuilder.java:2182) 
    at java.time.format.DateTimeFormatter.formatTo(DateTimeFormatter.java:1744) 
    at java.time.format.DateTimeFormatter.format(DateTimeFormatter.java:1718) 
+1

這工作對我來說 – Jerry06

+0

在這裏工作很好Java 1.8 – MadProgrammer

+0

我的不好,更新了問題,它是打印,不解析 – yegor256

回答

0

這是如何工作的:

String text = DateTimeFormatter.ISO_LOCAL_DATE 
    .withZone(ZoneId.of("UTC")) 
    .format(date.toInstant()); 
+2

而不是'ZoneId.of(「UTC」)',你也可以使用內置常量'ZoneOffset.UTC'。根據[javadoc](https://docs.oracle.com/javase/8/docs/api/java/time/ZoneId.html#of-java.lang.String-),它們是等效的:*「If區域ID等於'GMT','UTC'或'UT',那麼結果是ZoneId具有相同的ID和等同於ZoneOffset.UTC的規則。* – 2017-10-18 10:51:28

1

這是因爲Instant類表示時間軸上的一點:unix時代以來的納秒數(1970-01-01T00:00Z),沒有任何時區概念 - 因此它沒有特定日期/時間(日/月/年,小時/分鐘utes /秒),因爲它可以代表不同時區的不同日期和時間。

設置格式化程序中的特定區域like you did可將Instant轉換爲該區域(以便自時代以來的納秒數可以轉換爲特定的日期和時間),從而可以對其進行格式化。

對於這個特定的情況下,你只想在ISO8601 format日期部分(日,月,年),這樣一個方案是將Instant轉換爲LocalDate並調用toString()方法。當您在格式設置UTC,我使用的是相同的,將其轉換:

String text = date.toInstant() 
    // convert to UTC 
    .atZone(ZoneOffset.UTC) 
    // get the date part 
    .toLocalDate() 
    // toString() returns the date in ISO8601 format 
    .toString(); 

這回同樣的事情your formatter。當然對於其他格式,您應該使用格式化程序,但專門用於ISO8601,則可以使用toString()方法。


你也可以轉換Instant到你想要的時區(在這種情況下,UTC)並將其直接傳遞到格式:

String text = DateTimeFormatter.ISO_LOCAL_DATE.format(
    date.toInstant().atZone(ZoneOffset.UTC) 
); 

唯一的區別是,當你設置格式化程序中的區域,日期在格式化時轉換爲該區域(當您未設置時,日期不轉換)。