0

我正在通过 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 convertCurrentDate = sdf.parse(elem1);' 是导致错误的行。

谢谢!

4

2 回答 2

1

我也很难过我的机器上的以下测试通过

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 存在问题。

还可以尝试上面的测试,该测试消除了除日期代码之外的所有内容。

于 2015-08-22T00:12:52.827 回答
0

这是执行此操作的简单示例:

SimpleDateFormat formatter = new SimpleDateFormat("dd-MMM-yyyy");
String dateInString = "7-Jun-2013";
try {
    Date date = formatter.parse(dateInString);
    System.out.println(date);
    System.out.println(formatter.format(date));
} catch (ParseException e) {
    e.printStackTrace();
}

Java 8 更新

String string = "August 21, 2015";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MMMM d, yyyy", Locale.ENGLISH);
LocalDate date = LocalDate.parse(string, formatter);
System.out.println(date); // 2015-09-21

我想这就是你想要的。很乐意帮助谢谢

于 2015-08-21T16:18:00.217 回答