我尝试在将java.util.Date
转换为java.sql.Timestamp之后插入java.util.Date utilDate = new java.util.Date();
java.sql.Timestamp sq = new java.sql.Timestamp(utilDate.getTime());
并使用以下代码段:
sq
但这会给我2014-04-04 13:30:17.533
{{1}}
有没有办法在没有毫秒的情况下获得输出?
答案 0 :(得分:43)
您可以使用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()));
输出:
2014-04-04 10:10:17.78
2014-04-04 10:10:17.0
答案 1 :(得分:12)
看看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));
答案 2 :(得分:8)
问题在于您打印时间数据的方式
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
答案 3 :(得分:3)
我建议使用apache.commons库中的DateUtils。
long millis = DateUtils.truncate(utilDate, Calendar.MILLISECOND).getTime();
java.sql.Timestamp sq = new java.sql.Timestamp(millis );
修改:修正Calendar.MILISECOND
至Calendar.MILLISECOND
答案 4 :(得分:1)
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);
这给了我以下输出:
utilDate:Fri Apr 04 12:07:37 MSK 2014
sqlDate:2014-04-04