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 to Long type and report an error.

String type = result.getClass().getName();
if ("java.sql.Timstamp".equalsIgnoreCase(type)) {
    
    
      return new Date((Long) result);
}

2. Solutions

Because java.sql.Timestamp is a subclass of java.util.Date;
therefore, just convert java.sql.Timestamp to java.util.Date type directly.

String type = result.getClass().getName();
if ("java.sql.Timestamp".equalsIgnoreCase(type)) {
    
    
    return (Date)result;
}

Or convert the data into String type output:

String type = result.getClass().getName();

 // 将 Timestamp 类型转换为 String类型(yyyy-MM-dd HH:mm:ss)
 if ("java.sql.Timestamp".equalsIgnoreCase(type)) {
    
    
     //java.sql.Timestamp处理逻辑
     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";

    /**
     * 将Date转成 String,格式:yyyy-MM-dd HH:mm:ss
     * @param date 日期类型
     * @return String 日期格式的字符串
     */
    public static String timeToYmdHmsString(Date date) {
    
    
        SimpleDateFormat formatter = new SimpleDateFormat(defaultYmdHmsPattern);
        return formatter.format(date);
    }
}

Guess you like

Origin blog.csdn.net/aikudexiaohai/article/details/131654973