SQL and Java return different dates? - java

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?

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.

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

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

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

Related

Why querying a date BC is changed to AD in Java?

My program in Java connects to a Database (Oracle XE 11g) which contains many dates (date format of OracleXE is set to syyyy/mm/dd).
Doing a query in the database with negative dates (before Christ) works fine. When I do it in Java, they are all changed to AD (Anno Domini). How can I retrieve dates in Java respecting AD/BC?
My Java code here does the query to the DB and puts the result in a table.
try {
Object item=cbPD.getSelectedItem();
String dacercare=item.toString();
query = "SELECT DISTINCT PD.Titolo,PD.Inizio,(Select E.nome From Evento E WHERE PD.Inizio_Evento=E.CODE),
PD.Fine, (Select E.nome From Evento E WHERE PD.Fine_Evento=E.CODE ) FROM Periododelimitato PD WHERE PD.Titolo=?";
PreparedStatement stAccess = Login.connessione.prepareStatement(query, ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
stAccess.setString(1,dacercare);
rset = stAccess.executeQuery();
j = modelPD.getRowCount();
for (i=0; i<j; i++) modelPD.removeRow(0);
Date data;
while (rset.next()) {
data = rset.getDate(2);
modelPD.addRow(new Object[]{rset.getString(1),data, rset.getString(3), rset.getString(4), rset.getString(5)});
}
}
Here an Example using a specific Query:
try {
query = "SELECT PD.Inizio FROM PeriodoDelimitato PD WHERE PD.CodP=?";
String dacercare="8"; //look for record with this specific Primary key
PreparedStatement stAccess = Login.connessione.prepareStatement(query,
ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
stAccess.setString(1, dacercare);
rset = stAccess.executeQuery();
while(rset.next()) {
Date dateBC = rset.getDate(1);
modelPD.addRow(new Object[]{null, dateBC, null, null, null});
}
Output in Java is:
0509-01-01
Output using the same query (substituing ? with the primary key specified) in Sql developer:
-0509/01/01
Note on the query: the column selected in this example is in Oracle a DATE type.
Adding information: DBMS is Oracle (XE 11g), DB has been built on IDE (SQL developer). The program is written in Java through Netbeans 8.2. I connect to the database in Netbeans adding the Library "ojdbc6.jar".
First, it’s not immediately clear how you should handle historic and not least prehistoric dates and how you should expect them to behave. It’s not something I know, but I doubt that any calendar in common use today was used in the 6th century BCE (before the common era, “BC”). Maybe you were already aware, I just wanted to mention it for anyone else reading this answer.
With thanks to Basil Bourque’s (now deleted) answer, what you have observed seems to be the intended behaviour with java.sql.Date. I tried printing dates from year 2 CE (common era, “AD”) and then year 2 BCE and compared. First 2 CE:
LocalDate ld = LocalDate.of(2, 1, 1);
java.sql.Date sqlDate = java.sql.Date.valueOf(ld);
System.out.println("java.sql.Date " + sqlDate + " millis " + sqlDate.getTime());
java.sql.Date 0002-01-01 millis -62104237200000
This is as expected. For 2 BCE we need to supply -1 to LocalDate since 0 means 1 BCE, and -1 means 2 BCE. Insert LocalDate.of(-1, 1, 1) in the above code, and the output is
java.sql.Date 0002-01-01 millis -62198931600000
We note that the date is printed the same. 0002 is hardly downright incorrect, but it doesn’t tell us whether it’s year 2 CE or BCE. I believe that this explains the behaviour you observed. Next we note that the millisecond values are different, so the dates are different as they should be. The diffirence is 94694400000 milliseconds, which equals 1096 days or 3 years if one of them is a leap year. The leap year may surprise, but otherwise I think it’s correct.
There is something fishy, though. When I converted the sql date back into a LocalDate, the era was lost, I always got a date in the common era. Since you don’t need this conversion, you probably don’t need to care.
I believe the good solution will be to drop the outdated Date class completely and use the modern LocalDate throughout. You should be aware that this follows the so-called proleptic Gregorian calendar, which may not always give the exact same dates as Date. Also this requires JDBC 4.2 compliant driver, so your ojdbc6.jar won’t do. Even though this may mean you’re prevented, I am letting the suggestion stand for anyone else reading along. I have not tested, but I think the following should work:
LocalDate dateBC = rset.getObject(1, LocalDate.class);
A solution using the old Date type to query SQL dates BC and AC that is working is to declare into my class a SimpleDataFormat with the format specified below
public SimpleDateFormat sdf= new SimpleDateFormat("yyyy-MM-dd G");
Then I declared a Date dataOUT invoking the format method of SimpleDataFormat giving as input the Date BC queried from the Database
dataOUT=sdf.format(rset.getDate(2));
Thank you all for the time dedicated to my question!

JDBC SQL Time zone

I'm using Spring with apache commons BasicDataSource.
The time zone shows as GMT via:
SELECT ##global.time_zone, ##session.time_zone;
My input is in epoch time, 1386831420000 and 1386833220000, so the query should be like this:
SELECT * FROM table WHERE AND arrival_time BETWEEN '2013-12-12 06:57:00' AND '2013-12-12 07:27:00';
I enabled SQL profiing, and this is the query that actually gets executed, so I don't get the correct results:
SELECT * FROM table WHERE AND arrival_time BETWEEN '2013-12-12 01:57:00' AND '2013-12-12 02:27:00';
Notice that the times are off by 5 hours, since I am EST-5, and the time should be in GMT.
My question is: How can I tell MySQL or Spring JDBC not to use the client time zone, and simply to always use GMT?
Please comment if there is any detail I could add to solve the issue.
Try explicitly converting the date string into a date type using TO_DATE (or implementation specific date converter function)
SELECT *
FROM table
WHERE arrival_time BETWEEN
TO_DATE('2013-12-12 06:57:00', 'YYYY-MM-DD HH24:MI:SS')
AND
TO_DATE('2013-12-12 07:27:00', 'YYYY-MM-DD HH24:MI:SS')
The above example is in Oracle SQL but the principle of explicitly casting a date string to a date type is common throughout SQL implementations.
It sounds like the JDBC driver isn't properly detecting Mysql's time zone setting. You may need to specify the server's time zone in the connection string. Try adding
serverTimezone=UTC&useTimezone=true
to the connection string. For more information, refer to the JDBC doc at http://cs.wellesley.edu/~cs304/jdbc/connector-j.html#connector-j-reference

How to parse this "31/10/13" to Oracle date in Java

I make an application based on hibernate,
I just wanna ask,
How to parse this "31/10/13" to Oracle date in Java,
before this, I've try this method
SimpleDateFormat sdf1 = new SimpleDateFormat("dd/MM/yyyy");
Date log_date = sdf1.parse(tgl1);
it works, but when I try to make a simple query to search data like this
select * from coreservice where log_date='31-OCT-13';
but I got no data found in result....
Any help will be pleasure :)
Use oracle to_date functionin your query as follows:
select * from coreservice where log_date = to_date('31-OCT-2013','dd/mon/yyyy');

Error while storing jXDatePicker1 Date value in database

I am using swingxLabs' component jXDatePicker1 to pick date in a graphical format and trying to store it in the database made in derby. My code was this:
Date date=jXDatePicker1.getDate();
PreparedStatement statement = connect
.prepareStatement("INSERT INTO BILLING (DATE, DHRNUMBER) VALUES('"+date+"', "+dhrNumber+")");
The error which i am getting is:
java.sql.SQLDataException: The syntax of the string representation of a datetime value is incorrect.
Am i doing it right? Or there can be some other way to solve this.
Thanks
Derby's built-in DATE datatype supports a short list of string formats: http://db.apache.org/derby/docs/10.9/ref/rrefsqlj18730.html
Since you are using PreparedStatement, the best thing to do is to prepare the statement
INSERT INTO BILLING (DATE, DHRNUMBER) VALUES(?,?)
and then substitute your actual values using the setDate() and setInt() methods from:
http://docs.oracle.com/javase/6/docs/api/java/sql/PreparedStatement.html
This alternative totally worked for me:
Date d=jXDatePicker1.getDate();
System.out.println(d);
DateFormat df=new SimpleDateFormat("MM/dd/yyyy");
String date=df.format(d);
System.out.println(date);
PreparedStatement statement = connect
.prepareStatement("INSERT INTO BILLING (DATE) VALUES('"+date+"')");

Default JDBC date format when reading date as a string from ResultSet

I'm looking at some code that basically does the following:
ResultSet rs = ps.executeQuery();
String myDateStr = rs.getString("MY_DATE"); //field is of type Date
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss'.0'");
Date myDate = sdf.parse(myDateStr);
On some environments the last line works, and on others it throws an Unparseable date exception. It looks like on some systems the default date format is 2013-01-25 00:00:00.0, and on others 2013-01-25 00:00:00.
The JVM, OS and Oracle version are different between the environments (all use Oracle and run on a unix variant though).
Changing the code might be complex. I'm wondering if there is an environment variable or similar that can be set to make the date format returned from rs.getString() consistent?
try this:
ResultSet rs = ps.executeQuery();
Date myDate = rs.getDate("MY_DATE");
or this :
ResultSet rs = ps.executeQuery();
String myDateStr = rs.getString("MY_DATE");
Date myDate = valueOf(myDateStr);
More about date: http://docs.oracle.com/javase/7/docs/api/java/sql/Date.html
More about ResultSet : http://docs.oracle.com/javase/7/docs/api/java/sql/ResultSet.html
Instead of using
String myDateStr = rs.getString("MY_DATE")
you should use
Timestamp timestamp = rs.getTimestamp("MY_DATE");
JDBC / Database will handle the date transformation for you.
If the field is of type Date, then read it as a java.sql.Date and do whatever conversion you need after that. Otherwise you're at the mercy of the database implementation.
For the Oracle JDBC driver I am using, the format is hard-coded in the driver library, so should only differ across systems if different driver versions are in use.
See my attempt to get an answer to the same question here: Where is the date format specified when reading a date as a string from JDBC ResultSet.
(Apologies for asking a separate question, but as your question had been answered multiple times with the ever-helpful "just don't do that" response, I tried again...).

Categories