如何将 java.util.Date 转换为时间戳中的当前时间..?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12970638/
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 convert java.util.Date into current time in timestamp..?
提问by codeofnode
i am making a program in java. i am using the following code
我正在用java制作一个程序。我正在使用以下代码
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
?
上面的函数接受参数 asjava.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.
任何人都可以帮助如何编码,以便我可以在表中插入系统的当前时间戳。谢谢。
回答by Grisha Weintraub
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())
回答by Drogba
Date now = new Date();
now.getTime();
回答by ppeterka
You could also just issue an SQL statement:
你也可以只发出一条 SQL 语句:
UPDATE MY_TABLE SET LAST_LOGIN = NOW();
This is for MySQL. You should also find this helpful: MySQL Date and Time functions
这是针对 MySQL 的。您还应该发现这很有帮助:MySQL 日期和时间函数
EDITAs Rambo requested, setting default value of a column to the actual timestamp (As per MySQL: ALTER TABLE syntaxand MySQL Data type default values):
编辑根据 Rambo 的要求,将列的默认值设置为实际时间戳(根据MySQL:ALTER TABLE 语法和MySQL 数据类型默认值):
ALTER TABLE MY_TABLE ALTER MY_TIMESTAMP COLUMN SET DEFAULT CURRENT_TIMESTAMP;
回答by Puce
With JPA:
使用 JPA:
annotate lastLogin with: @Temporal(TemporalType.TIMESTAMP)
注释 lastLogin : @Temporal(TemporalType.TIMESTAMP)
With JDBC:
使用 JDBC:
回答by NPKR
use this to java.sql.Timestamp timestamp = new java.sql.Timestamp(new Date().getTime());
用这个 java.sql.Timestamp timestamp = new java.sql.Timestamp(new Date().getTime());
u.setLastlogin(timestamp);