Get the time value from the database and report an error: Java sql. Timestamp cannot be cast to java. lang.Long
1. Problem description
Convert the queried timestamp type data in the database into long type and report an error.
String type = result.getClass().getName(); if ("java.sql.Timstamp".equalsIgnoreCase(type)) { return new Date((Long) result); }
2. Solution
Because Java sql.Timestamp is Java util. Subclass of date;
So, just put Java sql.Timestamp to Java util.Date type is enough.
String type = result.getClass().getName(); if ("java.sql.Timestamp".equalsIgnoreCase(type)) { return (Date)result; }
Or convert the data to string type output:
String type = result.getClass().getName(); // Convert Timestamp type to String type (yyyy-MM-dd HH:mm:ss) if ("java.sql.Timestamp".equalsIgnoreCase(type)) { //java.sql.Timestamp processing logic return DateUtil.timeToYmdHmsString((Date)result); }
The dateutil tool class is as follows:
public class DateUtil { private static String defaultYmdHmsPattern = "yyyy-MM-dd HH:mm:ss"; /** * Convert Date to String, format: yyyy-MM-dd HH:mm:ss * @param date date type * @return String Date format string */ public static String timeToYmdHmsString(Date date) { SimpleDateFormat formatter = new SimpleDateFormat(defaultYmdHmsPattern); return formatter.format(date); } }
Similar Posts:
- [Solved] java.lang.IllegalArgumentException: Cannot format given Object as a Date
- On the non thread safety problem of simpledateformat and its solution
- MySQL from_ Unixtime() and UNIX_ The difference of timestamp() function
- [How to Solve] Failed to convert value of type ‘java.lang.String’ to required type ‘java.util.Date’;
- Convert Object to List>, avoiding Unchecked cast: ‘java.lang.Object’ to ‘java.util.List
- C# String was not recognized as a valid DateTime [How to Solve]
- Springboot uses the Datetimeformat (pattern = “yyyy MM DD HH: mm: SS”) annotation to automatically convert the string to date type error
- JAVA Error: Failed to convert property value of type ‘java.lang.String‘ to required type ‘java.util.Date
- HDFS: How to Operate API (Example)
- Roman to Integer LeetCode Java