[英]How to convert date-time “yyyy/MM/dd HH:mm:ss” that's stored in a String to a Date object?
I want to insert into a Mysql column (DATETIME column) a time & date . 我想将时间和日期插入Mysql列(DATETIME列)中。 For that purpose i use the DATETIME field . 为此,我使用DATETIME字段。
But on the JAVA side , I need to have a Date object with the time & date . 但是在JAVA方面,我需要具有日期和时间的Date对象。
Consider the code : 考虑代码:
Calendar cal = Calendar.getInstance();
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
String str = dateFormat.format(cal.getTime());
System.out.println(str);
This code produces : 此代码产生:
2014/03/19 01:11:35
How can I convert it to a Date object in the format yyyy/MM/dd HH:mm:ss
, so it would be possible to put it in the mysql column of DATETIME ? 如何将其转换为yyyy/MM/dd HH:mm:ss
格式的Date对象,因此可以将其放在DATETIME的mysql列中?
Much appreciated 非常感激
The getTime()
method of Calendar returns a Date object. Calendar的getTime()
方法返回一个Date对象。
For JDBC, you'll use a java.sql.Timestamp
to preserve the time component. 对于JDBC,您将使用java.sql.Timestamp
保留时间组件。 (I think a java.sql.Date
loses the time component.) (我认为java.sql.Date
失去了时间部分。)
For example: 例如:
preparedStatement.setTimestamp(new java.sql.Timestamp(cal.getTime()));
First point: Date
objects have no "format" - they just represent an instant in time. 第一点: Date
对象没有“格式”-它们只是表示时间的瞬间。
If you print them, you get the default toString()
implementation for Date
. 如果打印它们,则将获得Date
的默认toString()
实现。
Second point: You don't need to format a Date
to use it with JDBC. 第二点:您无需格式化Date
即可将其与JDBC一起使用。
You should use a prepared statement, then call setObject()
, to set the parameter value - the JDBC driver will do the rest, including wrapping in quotes if that's required for the data type. 您应该使用一条准备好的语句,然后调用setObject()
来设置参数值-JDBC驱动程序将完成其余工作,如果数据类型需要这样做,包括用引号引起来。
Final point: Never use Calendar
unless you have to. 最后一点:除非必须 ,否则不要使用Calendar
。
In this case, simply new Date()
will do the job. 在这种情况下,只需new Date()
完成工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.