Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
207 views
in Technique[技术] by (71.8m points)

how to convert String to java.sql.Date?

I need to convert a string in the format i.e. "jan 25,2021" to a java.sql.date in the format "2021-01-25". I tried to use this code:

String date = "jan 25,2021";
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
java.sql.Date booking_date=null;
try{
java.util.Date util_date = format.parse(date);
booking_date = new Date(util_date.getTime());
}
catch(ParseException e){
            System.out.println(e);
        }

But always throws a ParseException. Where is the mistake?

question from:https://stackoverflow.com/questions/65886788/how-to-convert-string-to-java-sql-date

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I need to convert a string in the format i.e. "jan 25,2021" to a java.sql.date in the format "2021-01-25". I tried to use this code:

That's like asking: "How do I convert a painting into an audio file" - these 2 concepts are unrelated. They sound related (jan 25, 2021 is a date, and, well, java.sql.Date, it's right there in the name, isn't it), but they are not: java.sql.Date is a misnomer - it does not represent a date at all; it represents an instant in time. Which is not a date: If I clap my hands and ask everybody around the world what date it is when I did that, you'll get at least 2 different answers, thus proving that these 2 are not the same.

The right solution is to use the newer API which doesn't suffer from such errors:

DateTimeFormatter FORMAT = DateTimeFormatter.ofPattern("MMM dd,uuuu", Locale.ENGLISH);
LocalDate ld = LocalDate.parse("jan 25,2021", FORMAT);

I would expect .setObject(x, someLocalDate) to work as a date value, but if it doesn't (and it may not - mysql is notoriously bad, and its JDBC driver is dubious as well), at least convert from the proper representation (LocalDate) to the broken one (java.sql.Date) as late as possible - don't let that error infect your java code. Same goes in reverse: When retrieving dates, use .getObject(idx, LocalDate.class), and if that does not work, convert from the broken java.sql.Date to the correct java.time.LocalDate immediately, prevent that error from infecting your java code as much as possible.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...