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 appears that datetime is more common than timestamp). My code to set the date looks like this:
我在我的mysql数据库上使用datetime字段(因为看起来datetime比timestamp更常见)。我设置日期的代码如下所示:
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();
3 个解决方案
#1
28
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只是日期,无论它存储在哪个列的类型。
#2
4
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.
期望列类型为Date。所以它正常化它,消除时间。
Try
尝试
ps.setTimetamp();
#3
-4
You could use :
你可以使用:
private static String getTimeStamp() {
SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
return f.format(new Date());
}
#1
28
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只是日期,无论它存储在哪个列的类型。
#2
4
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.
期望列类型为Date。所以它正常化它,消除时间。
Try
尝试
ps.setTimetamp();
#3
-4
You could use :
你可以使用:
private static String getTimeStamp() {
SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
return f.format(new Date());
}