[英]parse string into date format
I am importing data from a csv file via opencsv to insert into a mysql DB. 我正在通过opencsv从csv文件导入数据以插入到mysql数据库中。 opencsv imports as string and for 1 field in the DB I need to parse it to date in the format: yyyy-MM-dd.
opencsv作为字符串导入,对于数据库中的1个字段,我需要以yyyy-MM-dd格式将其解析为最新日期。 However I am getting an error.
但是我遇到一个错误。
// 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);
As mentioned above printing date out to console gives me 2015-08-14. 如上所述,打印日期到控制台给了我2015-08-14。 However I get the error:
但是我得到了错误:
java.text.ParseException: Unparseable date: ""
Can someone give me some advice as to what I am doing wrong? 有人可以给我一些有关我做错事情的建议吗?
The line 'java.util.Date convertedCurrentDate = sdf.parse(elem1);' 行'java.util.Date convertedCurrentDate = sdf.parse(elem1);' is the line causing the error.
是导致错误的行。
Thanks! 谢谢!
I am stumped also the following test passes on my machine 我也很沮丧,以下测试通过了我的机器
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);
}
}
What version of Java are you running? 您正在运行什么版本的Java? I know there was an issue in the latest java 8 (8u61) and JodaTime.
我知道最新的Java 8(8u61)和JodaTime中存在问题。
Also try the test above that eliminates everything but the Date code. 另外,请尝试进行上述测试,以消除除日期代码之外的所有内容。
Here is the Simple Example to do that : 这是执行此操作的简单示例:
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 update 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
i think this is what you want .Happy to help thanks 我认为这就是您想要的。很高兴为您提供帮助
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.