[英]How to convert java.util.Date into current time in timestamp..?
i am making a program in java. 我正在用java创建一个程序。 i am using the following code 我使用以下代码
u.setLastlogin(new java.util.Date());
above function accepts parameter as java.util.Date
but i want to store this value in a database table where the column is of type timestamp
? 上面的函数接受参数为java.util.Date
但我想将此值存储在数据库表中,其中列的类型为timestamp
?
can any one help how to code so that i can insert the current timestamp of the system in the table. 任何人都可以帮助如何编码,以便我可以在表中插入系统的当前时间戳。 thanks. 谢谢。
You can convert Date
to Timestamp
as follows: 您可以将Date
转换为Timestamp
,如下所示:
Timestamp timestamp = new Timestamp(date.getTime());
And if you want timestamp of current date: 如果你想要当前日期的时间戳:
new Timestamp(System.currentTimeMillis())
Date now = new Date();
now.getTime();
You could also just issue an SQL statement: 您也可以发出一条SQL语句:
UPDATE MY_TABLE SET LAST_LOGIN = NOW();
This is for MySQL. 这是针对MySQL的。 You should also find this helpful: MySQL Date and Time functions 您还应该发现这有用: MySQL日期和时间函数
EDIT As Rambo requested, setting default value of a column to the actual timestamp (As per MySQL: ALTER TABLE syntax and MySQL Data type default values ): 编辑当Rambo请求时,将列的默认值设置为实际时间戳(根据MySQL:ALTER TABLE语法和MySQL数据类型默认值 ):
ALTER TABLE MY_TABLE ALTER MY_TIMESTAMP COLUMN SET DEFAULT CURRENT_TIMESTAMP;
With JPA: 使用JPA:
annotate lastLogin with: @Temporal(TemporalType.TIMESTAMP)
使用以下命令注释lastLogin: @Temporal(TemporalType.TIMESTAMP)
With JDBC: 使用JDBC:
PreparedStatement#setTimestamp PreparedStatement的#的setTimestamp
将此用于java.sql.Timestamp timestamp = new java.sql.Timestamp(new Date().getTime());
u.setLastlogin(timestamp);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.