如何使用java将当前日期和时间保存到数据库? [英] How to save current date and time to database using java?
本文介绍了如何使用java将当前日期和时间保存到数据库?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在使用以下代码来获取当前的日期和时间,但输出不是我所期望的,我无法将其保存到数据库中。
I am using the following code to get the current date and time, but the output is not what I am expecting and I cant save it into database.
输出>>当前:Tue Mar 05 09:58:26 EST 2013
Output >> current: Tue Mar 05 09:58:26 EST 2013
预期输出>>当前:2013-03-05 9:58:26
Expected output >> current: 2013-03-05 9:58:26
.....{
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
SimpleDateFormat parseFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = new Date();
try {
System.out.println("current: " +parseFormat.parse(dateFormat.format(date)));
return parseFormat.parse(dateFormat.format(date));
} catch (ParseException ex) {
Logger.getLogger(ConstructionModel.class.getName()).log(Level.SEVERE, null, ex);
}
return date;
}
......
ps.setDate(....) <<< failed
数据库
name type
mydate Date
推荐答案
p>您需要使用sql时间戳保存到数据库。将您的java.util.Date转换为 java.sql.Timestamp :
You need to use sql timestamp for saving to the database. Convert your java.util.Date to java.sql.Timestamp:
ps.setTimestamp(new java.sql.Timestamp(myDate.getTime()));
这篇关于如何使用java将当前日期和时间保存到数据库?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文