获得“解析异常”

问题描述 投票:0回答:2

我想字符串变成日期为甲,我使用SimpleDateFormat类。我传递字符串从字符串列表和String+Integer.toString(int)作为输入SimpleDateFormat pattern。注:除String+Integer.toString(int)的如果我通过实际的字符串,如“2019年1月9日”成功地转换为字符串的日期。我尝试了很多不同的东西。

dateList是“MMM DD”甲日期的列表。通过做dateList.get(5)+Integer.toString(year)这是给我解析异常<Jan 09 2019将字符串转换日期上甲添加的一年。 finalDatesInMMMDDYYYYFormat就是我节省了MMM DD yyyy格式的日期另一份清单。 Utils.parseDate是我在我提到的try-catch块utils的类写的方法。

int year = 2019;
private List<String> dateList = new ArrayList<>();
private List<Date> finalDatesInMMMDDYYYYFormat = new ArrayList<>();
final String testString = dateList.get(5)+Integer.toString(year);
finalDatesInMMMDDYYYYFormat.add(Utils.parseDate(testString, new SimpleDateFormat("MMM dd yyyy")));

预计:字符串更改到日期,并将其添加到finalDatesInMMMDDYYYYFormat

实际:获取解析异常。

java string parsing arraylist simpledateformat
2个回答
1
投票

java.time

    int year = 2019;
    DateTimeFormatter dateFormatter = new DateTimeFormatterBuilder()
            .parseCaseInsensitive()
            .appendPattern("MMM dd")
            .toFormatter(Locale.ENGLISH);

    List<LocalDate> finalDatesWithoutFormat = new ArrayList<>();

    String dateString = "JAN 09";
    MonthDay md = MonthDay.parse(dateString, dateFormatter);
    finalDatesWithoutFormat.add(md.atYear(year));

    System.out.println(finalDatesWithoutFormat);

从这段代码的输出是:

[2019-01-09]

java.time,现代Java的日期和时间API,包括没有一年,MonthDay的日期,这可能成为你的目的不是一个普通的日子好类。我的代码还演示了如何在一年提供获得LocalDate(没有一天的时间为准)。

我建议你不要使用DateSimpleDateFormat。这些类的设计不当,早已过时,后者尤其是出了名的麻烦。

出了什么错在你的代码?

从信息您提供它无法告诉你为什么代码没有工作。可能的解释包括以下内容,但也有可能是其他人。

  • 作为rockfarkas的另一种回答说,你的串联字符串时,你不把任何空间,月,年的天之间,但用于解析格式字符串所需要的空间存在。
  • 如果您的月的缩写都是英文的,例如,你的JVM的缺省语言环境不是英语,解析将失败(除非在本月缩写一致的极少数情况下)。你应该总是给你格式化语言环境来指定字符串中使用的语言来解析(或生产)。

顺便说一句,你的变量名finalDatesInMMMDDYYYYFormat是误导,因为一个Date还没有得到(不能)的格式。

链接


0
投票

如果你想解析格式"MMM dd yyyy",你应该添加一个额外的空间来测试字符串是这样的:

final String testString = dateList.get(5) + ' ' + year;
© www.soinside.com 2019 - 2024. All rights reserved.