我正在通过 opencsv 从 csv 文件导入数据以插入到 mysql 数据库中。 opencsv 作为字符串导入,对于数据库中的 1 个字段,我需要以以下格式解析它:yyyy-MM-dd。但是我收到错误。
// This is the string that I have extracted from the csv file
String elem1 = nextLine[0];
// printing out to console I can see the string I wish to convert
System.out.println(elem1); => 2015-08-14
// Below is my code to parse the date
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
java.util.Date convertedCurrentDate = sdf.parse(elem1);
String date=sdf.format(convertedCurrentDate );
// printing date to console gives me 2015-08-14
System.out.println(date);
如上所述,将日期打印到控制台给我的是 2015-08-14。但是我收到错误:
java.text.ParseException: Unparseable date: ""
有人可以给我一些关于我做错了什么的建议吗?
行“java.util.Date conversionCurrentDate = sdf.parse(elem1);”是导致错误的行。
谢谢!
最佳答案
我也对我的机器上通过的以下测试感到困惑
public class DateFormatterTest {
private static final String TEST_DATE = "2015-08-14";
@Test
public void SimpleDateFormatTest() throws ParseException {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
java.util.Date convertedCurrentDate = sdf.parse(TEST_DATE);
String date=sdf.format(convertedCurrentDate );
assertEquals(TEST_DATE, date);
}
}
您运行的 Java 版本是什么?我知道最新的 java 8 (8u61) 和 JodaTime 存在问题。
还可以尝试上面的测试,该测试消除了除日期代码之外的所有内容。
关于java - 将字符串解析为日期格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32144665/