One of the fields which I extract from a database is a date in string format and I need to convert it into a date type to compare with another date.
How do I do this please? Everything I have tried so far gives me an error of java.util.Date cannot be cast to java.sql.Date
and this is attempting the following example;
simpledateformat-gives-java-lang-classcastexception-java-util-date
An example of the date extracted in string format is "2012-10-15 09:00:29.157". I think the format to declare is yyyy-MM-dd HH:mm:ss.SSS but not sure.
Thanks
You can create a java.util.Date
from java.sql.Date
as follows:
java.util.Date date = new java.util.Date(resultSet.getDate("Column").getTime());
Alternatively you can convert the java.sql.Date
to either java.util.Calendar
or Joda library's DateTime and perform comparisons.
If you are looking at parsing date, then java.text.SimpleDateFormat
is your friend.
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
java.util.Date date = format.parse("2012-10-15 09:00:29.157");
It simply means you are assigning java.util.Date
in java.sql.Date
From your example you have to do following :
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
java.util.Date date = (java.util.Date)formatter.parse(""2012-10-15 09:00:29.157"");
Convert to Date
as Vikdor showed. then get the long timestamp = date.getTimestamp();
Now this long value is millisecons since 1970 utc. just compare by this value.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.