Hi i am trying to parse a string into a java.sql.date
Here is what i am doing
private static SimpleDateFormat sdfout = new SimpleDateFormat("yyyy.MM.dd.HH.mm");
try{
String date = "2010.09.30.13.18";
task.setDueDate(new java.sql.Date(sdfout.parse(date).getTime()));
}
The problem is that i only get the date back. Not the time.
Am i doing this correctly
We can convert String to Date in java using parse() method of DateFormat and SimpleDateFormat classes.
Date.parse() The Date.parse() method parses a string representation of a date, and returns the number of milliseconds since January 1, 1970, 00:00:00 UTC or NaN if the string is unrecognized or, in some cases, contains illegal date values (e.g. 2015-02-31).
To parse your "Thu Jun 18 20:56:02 EDT 2009" date string you need a SimpleDateFormat like this (roughly): SimpleDateFormat parser=new SimpleDateFormat("EEE MMM d HH:mm:ss zzz yyyy"); Use this to parse the string into a Date, and then your other SimpleDateFormat to turn that Date into the format you want.
The date function used to parse a date or datetime value, according to a given format string. A wide variety of parsing options are available.
The code logic is fine, you only need java.sql.Timestamp
instead of java.sql.Date
. The SQL timestamp represents both the date and time parts, like date in Java. The SQL date represents only the date part.
Noted should be that you should prefer java.util.Date
over java.sql.Timestamp
in the model objects and use the Timestamp
only at the very moment when you're about to set it in a SQL query. This separates the model objects from the JDBC API and improves their portability and reusability.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With