2017-08-06 802 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