如何在 Java 中使用 SQL Server 日期时间类型
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18631642/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to use SQL Server datetime type in Java
提问by Ufo.rob
I'm using Microsoft SQL Server 2008 R2, Java 7 and Microsoft JDBC Driver 4.0 for SQL Server.
我使用 Microsoft SQL Server 2008 R2、Java 7 和 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?
一旦我有一个名为 rs 的结果集,从日期时间列中获取“日期和时间”类型的最简单方法是什么,我可以从中提取日、月、年、小时、分钟和秒?
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.
对于其他类型,我可以简单地使用 rs.getString("column name") rs.getInt("column name") 等方法,但 getDate 返回日期类型,而 getHour() 等在文档中被标记为已弃用。
采纳答案by ug_
use rs.getDate("column name")
使用 rs.getDate("列名")
It will return a type java.sql.Date, this extends the class java.util.Datefrom there you can get all the date stuff you need.
它将返回一个类型java.sql.Date,它扩展了类java.util.Date从那里你可以获得你需要的所有日期内容。
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
你提到 .getHour() getDay() 等。折旧了,Java 日期包真的很笨而且制作很差。现在正在使用 Calendar 类,使用以下内容
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
java-forms.org 上的更多日历示例