将java日期转换为Sql时间戳

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22856931/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 18:26:11  来源:igfitidea点击:

Converting java date to Sql timestamp

javasqldatetimesqldatetime

提问by Shitu

I am trying to insert java.util.Dateafter converting it to java.sql.Timestamp and I am using the following snippet:

我试图java.util.Date在将其转换为 java.sql.Timestamp 后插入,我正在使用以下代码段:

java.util.Date utilDate = new java.util.Date();
java.sql.Timestamp sq = new java.sql.Timestamp(utilDate.getTime());

But this is giving me sqas 2014-04-04 13:30:17.533

但这给了我sq作为2014-04-04 13:30:17.533

Is there any way to get the output without milliseconds?

有没有办法在没有毫秒的情况下获得输出?

采纳答案by janos

You can cut off the milliseconds using a Calendar:

您可以使用以下方法截断毫秒数Calendar

java.util.Date utilDate = new java.util.Date();
Calendar cal = Calendar.getInstance();
cal.setTime(utilDate);
cal.set(Calendar.MILLISECOND, 0);
System.out.println(new java.sql.Timestamp(utilDate.getTime()));
System.out.println(new java.sql.Timestamp(cal.getTimeInMillis()));

Output:

输出:

2014-04-04 10:10:17.78
2014-04-04 10:10:17.0

回答by Markus

Take a look at SimpleDateFormat:

看看SimpleDateFormat

java.util.Date utilDate = new java.util.Date();
java.sql.Timestamp sq = new java.sql.Timestamp(utilDate.getTime());  

SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyyy HH:mm:ss");
System.out.println(sdf.format(sq));

回答by Reddy

The problem is with the way you are printing the Time data

问题在于您打印时间数据的方式

java.util.Date utilDate = new java.util.Date();
java.sql.Timestamp sq = new java.sql.Timestamp(utilDate.getTime());
System.out.println(sa); //this will print the milliseconds as the toString() has been written in that format

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
System.out.println(sdf.format(timestamp)); //this will print without ms

回答by nikis

java.util.Date utilDate = new java.util.Date();
java.sql.Date sqlDate = new java.sql.Date(utilDate.getTime());
System.out.println("utilDate:" + utilDate);
System.out.println("sqlDate:" + sqlDate);

This gives me the following output:

这给了我以下输出:

 utilDate:Fri Apr 04 12:07:37 MSK 2014
 sqlDate:2014-04-04

回答by Miron Balcerzak

I suggest using DateUtils from apache.commons library.

我建议使用 apache.commons 库中的 DateUtils。

long millis = DateUtils.truncate(utilDate, Calendar.MILLISECOND).getTime();
java.sql.Timestamp sq = new java.sql.Timestamp(millis );

Edit: Fixed Calendar.MILISECONDto Calendar.MILLISECOND

编辑:固定Calendar.MILISECONDCalendar.MILLISECOND