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

陌路散爱 提交于 2019-12-04 07:55:30

You need to use java.sql.Timestamp. java.sql.Date does not have a time component, so its time is always 00:00:00.

java.sql.Date don't retain the hours, minutes, seconds and milliseconds since it mirrors the date type in SQL. Simply ask for a java.sql.Timestamp instead of a Date. Since Timestamp is a subtype of java.util.Date, you can ask it directly.

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

You must be importing java.sql.Date. Instead use java.util.Date or java.util.Timestamp.

java.sql.Date will truncate time.

Thanks for all your response. I found a way to take the time.

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 allows us to use a better suited Date classes (in java.time.*). The convertion from LocalDate (java) to sql date is done by: java.sql.Date.valueOf(LocalDate.of(2012, Month.DECEMBER, 12))

Oracle advise to use java 8 Dates instead of the oldest version :

These classes had several drawbacks, including:

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.
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!