java.time
I recommend that you use java.time, the modern Java date and time API, for you date work. You can directly pass a java.time.LocalDate
to your SQL database via JDBC (since JDBC 4.2) or JPA (for example since Hibernate 5.0).
You need to specify which format to assume for parsing:
private static final DateTimeFormatter DATE_FORMATTER
= DateTimeFormatter.ofPattern("MM/dd/uuuu", Locale.ENGLISH);
The rest is straightforward:
String date = "09/17/2014";
LocalDate journeyDate = LocalDate.parse(date, DATE_FORMATTER);
System.out.println(journeyDate);
Output:
2014-09-17
I assumed that you were trying to specify that you wanted a java.sql.Date
because you needed it for use with an SQL database. But you don’t need no java.sql.Date
for that. For how to insert a LocalDate
into SQL, see the link at the bottom.
If you need a java.sql.Date
for a legacy API that you cannot afford to upgrade to java.time right now, the conversion is straightforward too:
java.sql.Date oldfashionedJavaSqlDate = java.sql.Date.valueOf(journeyDate);
System.out.println(oldfashionedJavaSqlDate);
2014-09-17
What happened in your code?
Jon Skeet has already pointed out the issues with your code. But only out of curiosity, more precisely, what happened? The no-arg SimpleDateFormat
constructor gives you a localized format for date and time in your default locale. For example for en-IN
locale the format could be like 17/09/14, 12:00 AM
. In this case your formatter would parse 09 as the day of month, 17 as the month and 2014 as the year and then complaint with the exception because the comma and time were not present in the string.
Links