Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I am using Spring JDBCTemplate to conneect DB. When I am selecting date in DB using below query

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

output is, 31-12-99 23:59:59.

But, when I am using the same with JDBCTemplate like below,

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

outpt is 2099-12-31 00:00:00.0.

Time is not correct. I also need the same time in Date class. How to get that?

like image 302
Samurai Avatar asked Jun 22 '13 10:06

Samurai


3 Answers

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

like image 143
Mark Rotteveel Avatar answered Oct 21 '22 02:10

Mark Rotteveel


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);
like image 24
user327961 Avatar answered Oct 21 '22 03:10

user327961


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

java.sql.Date will truncate time.

like image 37
Lokesh Avatar answered Oct 21 '22 04:10

Lokesh