我的问题如下.我正在读一个文件,它包含一堆CSV行.每行包含一些格式为22-mar-2010或类似的日期,即格式为dd-MMM-yyyy.我想将其转换为ISO格式,因此它成为2010-03-22.
我的代码看起来像这样:
private String convertDate(String date) {
DateTimeFormatter oldFormat = DateTimeFormatter.ofPattern("dd-MMM-yyyy", new Locale("en"));
LocalDate parsedDate = LocalDate.parse(date, oldFormat);
DateTimeFormatter newFormat = DateTimeFormatter.ISO_DATE;
String newDate = parsedDate.format(newFormat);
return newDate;
}
输入看起来像这样:
sdfdsfslk 28-mar-2007 dfdsljs
sdfdsfslk 20-apr-2014 dfdsljs
sdfdsfslk 13-oct-2005 dfdsljs
sdfdsfslk 20-may-2014 dfdsljs
sdfdsfslk 20-jan-2014 dfdsljs
sdfdsfslk 20-feb-2014 dfdsljs
如果包含上面的语言环境或使用withLocale(Locale.ENGLISH),则它会在第一行日期字符串处失败.例外是:
java.time.format.DateTimeParseException: Text '28-mar-2007' could not be parsed at index 3
如果我删除区域设置部分,只需:
DateTimeFormatter.ofPattern("dd-MMM-yyyy");
然后它会工作,直到它遇到像13-oct-2005这样的日期.它不喜欢英语’oct’并且在LocalDate.parse行失败.如果我将oct转换为okt(瑞典语,我在哪里),那么它会解析它.
我是否需要完全更改我的Locale或者这里出了什么问题?即使我在瑞典,我怎样才能用英语解析几个月的日期?