Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use SQL Server datetime type in Java

I'm using Microsoft SQL Server 2008 R2, Java 7 and Microsoft JDBC Driver 4.0 for SQL Server.

Once I have a ResultSet named rs what's the simplest method to get a "Date and Time" type from a datetime column from which I can extract day, month, year, hour, minute and second?

With other types I can simply use rs.getString("column name") rs.getInt("column name") etc. methods but getDate return a Date type and getHour() etc. are marked as deprecated in documentation.

like image 663
Ufo.rob Avatar asked Nov 02 '22 15:11

Ufo.rob


1 Answers

use rs.getDate("column name")

It will return a type java.sql.Date, this extends the class java.util.Date from there you can get all the date stuff you need.

You mentioned that the .getHour() getDay() ect. are depreciated, well java date packages are really dumb and made poorly. It is now using the Calendar class, use the following

Date d = rs.getDate("date_column");
Calendar c = Calendar.getInstance();
c.setTime(d.getTime());
int month = c.get(Calendar.MONTH);

More calendar examples at java-forms.org

like image 150
ug_ Avatar answered Nov 15 '22 06:11

ug_