java 从纪元时间/时间戳中删除毫秒 | 爪哇
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13115875/
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
Remove millisecond from epoch-time/timestamp | java
提问by sree127
I have with me an epoch time, which i would like to convert to an sql timestamp. I can extract the actual time from the epoch using this code :
我有一个纪元时间,我想将其转换为 sql 时间戳。我可以使用以下代码从纪元中提取实际时间:
String time = "1351504294";
long t = Long.parseLong(time);
Timestamp ts = new Timestamp(t*1000);
The output I'm getting is : 2012-10-29 09:58:50.0
.
But when i try to insert this into a table, it shows error because of the millisecond part, '09:58:50.0'. How can I remove the millisecond part from the timestamp?
我得到的输出是:2012-10-29 09:58:50.0
。但是,当我尝试将其插入表中时,由于毫秒部分“09:58:50.0”而显示错误。如何从时间戳中删除毫秒部分?
回答by Nathan Villaescusa
If you are adding the Timestamp
directly to the SQL statement then Java is calling the toString()
function wich always outputs the format yyyy-mm-dd hh:mm:ss.fffffffff
. There is nothing that you could do to the Timestamp
object that would eliminate the nanoseconds part.
如果您将Timestamp
直接添加到 SQL 语句,则 Java 将调用toString()
始终输出格式的函数yyyy-mm-dd hh:mm:ss.fffffffff
。您无法对Timestamp
消除纳秒部分的对象执行任何操作。
If you want just the yyyy-MM-dd hh:mm:ss
portion you could either do:
如果你只想要那yyyy-MM-dd hh:mm:ss
部分,你可以这样做:
Timestamp ts = new Timestamp(t*1000);
String s = ts.toString().split('\.')[0];
Or you could use SimpleDateFormat
:
或者你可以使用SimpleDateFormat
:
Timestamp ts = new Timestamp(t*1000);
String s = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(ts);
回答by Kumar Vivek Mitra
Try it this way....
试试这个方法....
public class Time {
public static void main(String[] args){
String time = "1351504294";
long t = Long.parseLong(time);
Timestamp ts = new Timestamp(t*1000);
String date = new SimpleDateFormat("YYYY-MM-dd hh:mm:ss").format(ts);
System.out.println(date);
}
}