java 如何使用java将当前日期和时间保存到数据库?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15212832/
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 save current date and time to database using java?
提问by Daniel Morgan
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.
我正在使用以下代码获取当前日期和时间,但输出不是我所期望的,我无法将其保存到数据库中。
Output >> current: Tue Mar 05 09:58:26 EST 2013
输出 >> 当前:美国东部标准时间 2013 年 3 月 5 日星期二 09:58:26
Expected output >> current: 2013-03-05 9:58:26
预期输出 >> 当前: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
Database
数据库
name type
mydate Date
回答by amphibient
You don't need to parse before formatting:
您不需要在格式化之前解析:
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = new Date();
String frmtdDate = dateFormat.format(date);
System.out.println("frmtdDate: " + frmtdDate);
However, if you are trying to fit the date into some DB statement, you should not do it in the form of text, instead use one of the JDBC setters that utilize java.sql.Date
or java.sql.Timestamp
但是,如果您尝试将日期放入某些 DB 语句中,则不应以文本形式进行,而应使用使用java.sql.Date
或java.sql.Timestamp
回答by Igor Rodriguez
You need to use sql timestamp for saving to the database. Convert your java.util.Date to java.sql.Timestamp:
您需要使用 sql 时间戳来保存到数据库。将您的 java.util.Date 转换为java.sql.Timestamp:
ps.setTimestamp(new java.sql.Timestamp(myDate.getTime()));
回答by Javier
format
takes a Date
and returns a formatted String
. parse
takes a formatted String
and returns a Date
object. When you do parseFormat.parse(dateFormat.format(date))
you are converting Date
to String
and to Date
again. The value that is printed is the default representation provided by Date.toString()
instead of the formatted string.
format
接受 aDate
并返回一个格式化的String
. parse
接受格式化String
并返回一个Date
对象。当您这样做时,parseFormat.parse(dateFormat.format(date))
您正在转换Date
为String
并Date
再次转换。打印的值是由Date.toString()
而不是格式化字符串提供的默认表示。
System.out.println("current: " +dateFormat.format(date));