DateTimeFormatter for Date to String抛出异常

时间:2017-11-06 09:19:22

标签: java

我正在尝试使用流和String对日期的DateTimeFormatter个数组进行排序。

public static String[] sortDatesAsString(DateTimeFormatter formatter, String[] dates) {
    return Arrays.stream(dates)
            .map(date -> LocalDate.parse(date, formatter))
            .collect(Collectors.toList())
            .stream().sorted()
            .map((d) -> d.format(formatter))
            .toArray(size -> new String[size]);
}

public static void main(String[] args) {
    String arr[] = new String[]{"02/02/2010", "3/11/2011", "11/3/2011", "4/4/2011"};
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("mm/dd/yyyy");
    System.out.println(Arrays.toString(sortDatesAsString(formatter, arr)));
}

尝试将已排序的日期格式化回String以返回时,我收到以下异常。

Exception in thread "main" java.time.format.DateTimeParseException: Text '02/02/2010' could not be parsed: Unable to obtain LocalDate from TemporalAccessor: {DayOfMonth=2, MinuteOfHour=2, Year=2010},ISO of type java.time.format.Parsed
at java.time.format.DateTimeFormatter.createError(DateTimeFormatter.java:1920)

我无法理解异常。

1 个答案:

答案 0 :(得分:2)

检查异常消息:

export class MyApp {
rootPage:any;
constructor(platform: Platform, statusBar: StatusBar,splashScreen: SplashScreen) {
platform.ready().then(() => {
this.rootPage = HomePage;
statusBar.styleDefault();
splashScreen.hide();
    });
  }
}

您可以看到它解析了您的日期

Exception in thread "main" java.time.format.DateTimeParseException: Text '02/02/2010' could not be parsed: Unable to obtain LocalDate from TemporalAccessor: {DayOfMonth=2, MinuteOfHour=2, Year=2010},ISO of type java.time.format.Parsed
at java.time.format.DateTimeFormatter.createError(DateTimeFormatter.java:1920)

这不是你想要的。 TemporalAccessor: { DayOfMonth=2, MinuteOfHour=2, Year=2010 } (m)不适合MinuteOfHour

如果您查看https://groups.google.com/forum/#!topic/openresty-en/m-5a1Xrpruw文档,则会看到LocalDate

Month

不是

Symbol  Meaning                     Presentation      Examples
------  -------                     ------------      -------
M/L     month-of-year               number/text       7; 07; Jul; July; J

请完整阅读例外,90%的时间,答案就在其中......