获取“解析异常”

我想将字符串更改为我正在使用SimpleDateFormat类的日期格式。我将字符串作为字符串String+Integer.toString(int)列表和SimpleDateFormat pattern输入传递。注意:String+Integer.toString(int)如果我传递像“Jan 09 2019”这样的实际字符串,而不是成功地将字符串转换为日期。我尝试了很多不同的东西。


dateList是“MMM dd”甲酸盐日期的列表。通过这样做在该甲酸盐上添加年份,这给了我解析异常 <<-- 如果我硬编码日期,例如将字符串转换为日期 dateList.get(5)+Integer.toString(year),则不是这个。是另一个列表,我以 MMM dd yyyy 格式保存日期。 是我在 Utils 类中编写的一种方法,其中我提到了 try-catch 块。Jan 09 2019finalDatesInMMMDDYYYYFormatUtils.parseDate


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


实际:获取解析异常。


跃然一笑
浏览 151回答 2
2回答

胡子哥哥

java.time&nbsp; &nbsp; int year = 2019;&nbsp; &nbsp; DateTimeFormatter dateFormatter = new DateTimeFormatterBuilder()&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .parseCaseInsensitive()&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .appendPattern("MMM dd")&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .toFormatter(Locale.ENGLISH);&nbsp; &nbsp; List<LocalDate> finalDatesWithoutFormat = new ArrayList<>();&nbsp; &nbsp; String dateString = "JAN 09";&nbsp; &nbsp; MonthDay md = MonthDay.parse(dateString, dateFormatter);&nbsp; &nbsp; finalDatesWithoutFormat.add(md.atYear(year));&nbsp; &nbsp; System.out.println(finalDatesWithoutFormat);此代码段的输出是:[2019-01-09]java.time 是现代 Java 日期和时间 API,包括一个用于不带年份的日期的类MonthDay,它可能比普通日期更好地满足您的目的。我的代码还显示了如何提供一年来获取LocalDate(没有时间的日期)。我建议你不要使用Dateand&nbsp;SimpleDateFormat。这些类设计不佳且早已过时,后者尤其是出了名的麻烦。你的代码出了什么问题?根据您提供的信息,无法判断您的代码为何不起作用。可能的解释包括以下,但可能还有其他解释。正如rockfarkas在另一个答案中所说,在连接你的字符串时,你没有在月份和年份之间放置任何空格,但是你用于解析的格式字符串需要一个空格。例如,如果您的月份缩写是英文,而您的 JVM 的默认语言环境不是英文,则解析将失败(除了月份缩写重合的极少数情况)。您应该始终为您的格式化程序提供一个语言环境,以指定要解析(或生成)的字符串中使用的语言。顺便说一句,您的变量名称finalDatesInMMMDDYYYYFormat具有误导性,因为 aDate没有(不能有)格式。

守候你守候我

如果你想解析格式"MMM dd yyyy",你应该像这样在你的测试字符串中添加一个额外的空格:final&nbsp;String&nbsp;testString&nbsp;=&nbsp;dateList.get(5)&nbsp;+&nbsp;'&nbsp;'&nbsp;+&nbsp;year;
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java