2017-08-06 805 views
-3

作爲DateTimeFormatter.ofLocalizedDateTime(FormatStyle dateStyle, FormatStyle timeStyle)方法的2個參數,我可以傳遞什麼?我試圖JavaDoc建議但我得到這個錯誤。我假設你明白DateTimeFormatter應該能夠像JavaDoc所暗示的那樣格式化LocalDate和/或LocalTime對象,並且我不認爲我誤解了,因爲JavaDoc顯示了它的一個示例。 :DateTimeFormatter.ofLocalizedDateTime的第二個參數的異常?

import java.time.*; 
import java.util.*; 
import java.time.format.*; 
class Main { 
    public static void main(String[] args) { 
    LocalDate pieDay = LocalDate.of(2017, Month.JANUARY, 23); 
    LocalTime midnight = LocalTime.of(0,0); 
    LocalDateTime pieTime = LocalDateTime.of(pieDay, midnight); 

    DateTimeFormatter f2 = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.SHORT, 
     FormatStyle.SHORT); 
    f2.format(pieDay); // Exception here at runtime 
    f2.format(pieTime); 
    } 
} 

這裏是我的這個實驗沙箱:https://repl.it/JzHb/28但請運行自己的這個代碼片斷的版本給它之前驗證你的答案。

Exception in thread "main" java.time.temporal.UnsupportedTemporalTypeException: 
    Unsupported field: ClockHourOfAmPm 
+0

它說'getDefault()'方法不存在,它不。你爲什麼認爲['FormatStyle'](https://docs.oracle.com/javase/8/docs/api/java/time/format/FormatStyle.html)有這樣一種方法? – Andreas

+0

對不起,這個混亂。我更新了我的問題。 – djangofan

+0

當然'f2.format(pieDay)'由於**'LocalDate'沒有*時間*字段**而導致'Unsupported field:ClockHourOfAmPm'失敗。如果您想格式化僅限日期的值,請使用'ofLocalizedDate()'。 – Andreas

回答

-1

好,回答我的問題是,我認爲創建DateTimeFormatter將在任何3個組合的工作:

  • 一個LOCALDATE的對象
  • 一個本地時間對象
  • 一個LocalDateTime對象

但是,看起來DateTimeFormatter不能格式化LocalDate或Lo calTime

LocalDate pieDay = LocalDate.of(2017, Month.JANUARY, 23); 
LocalTime midnight = LocalTime.of(0,0); 
LocalDateTime pieTime = LocalDateTime.of(pieDay, midnight); 

DateTimeFormatter f2 = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.FULL, FormatStyle.SHORT); 

//System.out.println(f2.format(midnight)); // this throws exception 
//System.out.println(f2.format(pieDay)); // this throws exception 

f2.format(pieTime); // this line works 

這不是顯而易見的JavaDoc如我所料它以靈活的方式工作,像老java.text.DateFormat中的類。

+0

錯! 'DateTimeFormatter'確實適用於所有3個類,只要您不要求它提供不可用的信息。您正在調用'ofLocalizedDateTime'(** DateTime **),這意味着它將格式化任何具有** Date **和** Time **(例如LocalDateTime)的'java.time'對象, OffsetDateTime'和'ZonedDateTime'。如果改爲使用'ofLocalizedDate'(僅限** Date **),那麼除了已經提到的三個對象之外,它不會要求格式化對象的時間,還可以格式化LocalDate對象。 – Andreas

+0

我已經在[我以前的評論](https://stackoverflow.com/questions/45535747/exception-with-the-2nd-parameter-of-the-datetimeformatter-oflocalizeddatetime?noredirect=1#comment78073259_45535747)中介紹了這一點:「 'f2.format(pieDay)'由於'LocalDate'沒有* time *字段而導致'Unsupported field:ClockHourOfAmPm'失敗。如果你想格式化一個只包含日期的值,可以使用'ofLocalizedDate()'「。 --- javadoc是正確的::'DateTimeFormatter' *可以*格式'LocalDate'對象,**如果你使用它的權利**。 – Andreas