如何使用java设置完整的日期和时间sql,而不仅仅是日期?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3677606/
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 do I set a full date & time sql using java, and not just the date?
提问by Adam Morris
I am trying to set a timestamp in my database using java, however in my table all I get is the date, and no time (i.e., looks like "2010-09-09 00:00:00").
我正在尝试使用 java 在我的数据库中设置时间戳,但是在我的表中,我得到的只是日期,而不是时间(即,看起来像“2010-09-09 00:00:00”)。
I am using a datetime field on my mysql database (because it appearsthat datetime is more common than timestamp). My code to set the date looks like this:
我使用我的mysql数据库中的日期时间字段(因为它似乎是日期时间是比较常见的比时间戳)。我设置日期的代码如下所示:
PreparedStatement ps = conn.prepareStatement("INSERT INTO mytable (datetime_field) VALUES (?)")
java.util.Date today = new java.util.Date();
java.sql.Date timestamp = new java.sql.Date(today.getTime());
ps.setDate(1, timestamp);
ps.executeUpdate();
How do I set the date to include the time?
如何设置日期以包含时间?
Edit:I changed the code as per below, and it sets both the date and the time.
编辑:我按照下面的方式更改了代码,并设置了日期和时间。
PreparedStatement ps = conn.prepareStatement("INSERT INTO mytable (datetime_field) VALUES (?)")
java.util.Date today = new java.util.Date();
java.sql.Timestamp timestamp = new java.sql.Timestamp(today.getTime());
ps.setTimestamp(1, timestamp);
ps.executeUpdate();
采纳答案by ColinD
Use java.sql.Timestamp
and setTimestamp(int, Timestamp)
. java.sql.Date
is date-only, regardless of the type of the column it's being stored in.
使用java.sql.Timestamp
和setTimestamp(int, Timestamp)
。java.sql.Date
仅限日期,无论它存储在何种类型的列中。
回答by Brad Goss
Not exactly sure what you need to use, but
不完全确定您需要使用什么,但是
ps.setDate();
expects a column type of Date. So it's normalizing it, removing the time.
期望列类型为日期。所以它正在规范化它,消除时间。
Try
尝试
ps.setTimetamp();
回答by oyo
You could use :
你可以使用:
private static String getTimeStamp() {
SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
return f.format(new Date());
}