previous_developer
previous_developer

Reputation: 11028

SQL and Java return different dates?

I am using sqljdbc4.jar to connect SQL Server from my java application. I have a date field in my table. It works normally when I check from Sql Server Management Studio. But in java, every date is 2 day missing.

For example;

my date : 2012-01-10

date in java : 2012-01-08

PreparedStatement stmt = conn.prepareStatement("SELECT * FROM table1", ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
ResultSet rs = stmt.executeQuery();
rs.next();
System.out.println(rs2.getDate("dateCol").toString());

Why?

Upvotes: 1

Views: 1926

Answers (4)

Susie
Susie

Reputation: 5148

I was faced with somewhat similar problem couple of weeks. I had to save a java date in an oracle table which is typed sql date. You can not directly cast a java date to sql date. The following is what I did.

java.util.Date jDate = myObj.getDate();
java.sql.Date sDate = new java.sql.Date(jDate.getTime());

Upvotes: 0

previous_developer
previous_developer

Reputation: 11028

I just tried sqljdbc4.jar version 4, it fixed. Also there is no problem with version 2. Only bugged version is 3. Download link for version 4.

Thanks for answers.

Upvotes: 1

shareef
shareef

Reputation: 9581

like @Eugenio Cuevas said please try formatting the date

Could you try using SimpleDateFormat with yyyy.MM.dd format instead of .toString method?

because looking at you date example ; may be its like a problem i faced before the difference is 2 day because

1- 2012-01-10 and 2012-01-08 yyyy-mm-dd 2- 12-01-10 and 12-01-08 yy-mm-dd

that what caused my problem

Upvotes: 0

Diego
Diego

Reputation: 36176

which version of SQL Server and which datatype are you using? There are 6 "date and time" data types on SQl Server 2008:

date
datetimeoffset
datetime2
smalldatetime
datetime
time

maybe the one you are using is not supported in Java or by the drive you are using. Specially if you are using Date which is new in SQL Server 2008

Upvotes: 0

Related Questions