1. 程式人生 > 其它 >從資料庫中取時間值,報錯:java.sql.Timestamp cannot be cast to java.lang.Long

從資料庫中取時間值,報錯:java.sql.Timestamp cannot be cast to java.lang.Long

從資料庫中取時間值,報錯:java.sql.Timestamp cannot be cast to java.lang.Long


1、問題描述

將資料庫中的查詢到的 timestamp型別的資料,轉成 Long型別報錯。

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

2、解決方案

因為 java.sql.Timestampjava.util.Date子類

所以,直接 將 java.sql.Timestamp 轉換為 java.util.Date 型別 即可。

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

或者將資料轉成String型別輸出:

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); }

DateUtil 工具類如下:

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); } }