簡體   English   中英

使用時間格式選擇日期查詢不適用於JDBCTemplate和util.Date

[英]Select date query with time format is not working with JDBCTemplate and util.Date

我正在使用Spring JDBCTemplate來連接數據庫。 當我使用以下查詢在DB中選擇日期時

select to_date(valid_to,'DD-MM-YYYY HH24:MI:SS') from composition

輸出是,31-12-99 23:59:59。

但是,當我使用JDBCTemplate時,如下所示,

Date d = jdbcTemplate.queryForObject("select to_date(valid_to,'DD-MM-YY HH24:MI:SS') from composition",Date.class);

00:00:00.0出現在2099-12-31。

時間不對。 我還需要Date類中的相同時間。 怎么做到的?

您需要使用java.sql.Timestamp java.sql.Date沒有時間組件,因此它的時間始終為00:00:00。

java.sql.Date不保留小時,分鍾,秒和毫秒,因為它鏡像SQL中的日期類型。 只需要一個java.sql.Timestamp而不是Date。 由於Timestamp是java.util.Date的子類型,因此您可以直接詢問它。

import java.util.Date;
import java.sql.Timestamp;

[...]

Date d = jdbcTemplate.queryForObject("select to_date(valid_to,'DD-MM-YY HH24:MI:SS') from index_composition", Timestamp.class);

您必須導入java.sql.Date 而是使用java.util.Datejava.util.Timestamp

java.sql.Date將截斷時間。

感謝您的回復。 我找到了一種花時間的方法。

String dateString = jdbcTemplate.queryForObject("select to_char(valis_to, 'DD-MM-YYYY HH24:MI:SS') from composition",String.class);
Date date = sdf.parse(dateString);

Java 8允許我們使用更適合的Date類(在java.time。*中)。 從LocalDate(java)到sql日期的轉換由以下完成: java.sql.Date.valueOf(LocalDate.of(2012, Month.DECEMBER, 12))

Oracle建議使用java 8 Dates而不是最舊版本:

這些類有幾個缺點,包括:

The Calendar class was not type safe.
Because the classes were mutable, they could not be used in multithreaded applications.
Bugs in application code were common due to the unusual numbering of months and the lack of type safety.

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM