Wednesday, June 20, 2018

java sql date time




When I insert a SQL DateTime to the database I get 2007-02-07 12:00:00.00



But I made the Date object like this : 2007-02-07 17:29:46.00



How to get the value of the seconds in the database. It always changes it back to 12:00:00.00



date.setYear(Integer.valueOf(parsedDate[2].replaceAll(" ", "")) - 1900);
date.setMonth(Integer.valueOf(parsedDate[0].replaceAll(" ", "")));
date.setDate(Integer.valueOf(parsedDate[1].replaceAll(" ", "")));

...
java.sql.Date sqlDate = new java.sql.Date(date.getTime());


Should I use any formatters?


Answer



java.sql.Date represents a date, not a date and time. From the docs:




To conform with the definition of SQL DATE, the millisecond values wrapped by a java.sql.Date instance must be 'normalized' by setting the hours, minutes, seconds, and milliseconds to zero in the particular time zone with which the instance is associated.





If you want to store a date and time, you should look for another type - e.g. java.sql.Timestamp. EDIT: That's not suggesting you use a TIMESTAMP column type - as paulsm4 says in the comments, that's a different thing. However, as far as I can see, JDBC only supports:




  • Date (no, you want a time too)

  • Time (no, you want a date too)

  • Timestamp (includes a date and time, but you don't want TIMESTAMP SQL semantics)




I would expect using the Java Timestamp type with a DATETIME column to work, although without the level of precision that Timestamp provides.



EDIT: After a bit more research, it looks like you may want to use the java.sql.Time type, but with special driver parameters - at least if you're using the Microsoft driver. See these docs on configuring JDBC for more information.


No comments:

Post a Comment

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...