Java格式自定义日期到MySQL日期时间

Java格式自定义日期到MySQL日期时间,java,mysql,date,format,Java,Mysql,Date,Format,我有一个字符串,其值的格式为:01-Jul-2011 12:52:00 我想将其格式化以插入类型为DATETIME的MySQL数据库 我意识到我需要在01-07-2011 12:52:00表格中填写,但我不知道该怎么做 有什么解决方案吗?@Jigar是正确的,如果不是简洁的话。但看起来你可能需要更多的信息,我会用勺子给你 首先,你不应该试图格式化一个适合mysql的日期。您应该将日期作为参数传递给sql查询(而不是构建sql字符串) 要从输入中解析日期,请尝试以下代码: public stati

我有一个字符串,其值的格式为:01-Jul-2011 12:52:00

我想将其格式化以插入类型为DATETIME的MySQL数据库

我意识到我需要在01-07-2011 12:52:00表格中填写,但我不知道该怎么做


有什么解决方案吗?

@Jigar是正确的,如果不是简洁的话。但看起来你可能需要更多的信息,我会用勺子给你

首先,你不应该试图格式化一个适合mysql的日期。您应该将日期作为参数传递给sql查询(而不是构建sql字符串)

要从输入中解析日期,请尝试以下代码:

public static void main(String[] args) throws Exception {
    String input = "01-Jul-2011 12:52:00";
    SimpleDateFormat format = new SimpleDateFormat("dd-MMM-yyyy HH:mm:ss");
    Date date = format.parse(input);
    System.out.println(date); // "Fri Jul 01 12:52:00 EST 2011"
}
下面是一个使用JDBC连接器传递参数进行sql调用的示例:

Date date = format.parse(input);
jdbcConnection.createStatement().execute("insert into mytable (id, some_date) values (?, ?)", new Object[]{1, date});
您不必担心如何格式化mysql的日期,让JDBC驱动程序为您这样做吧

I suppose you mean you need to get the form "2011-07-01 12:52:00"? Here is a some example to convert between the two date representations:

String input = "01-Jul-2011 12:52:00";
java.util.Locale locale = new java.util.Locale("EN", "gb");
java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("dd-MMMM-yy HH:mm:ss", locale);
try
{
    java.util.Date date = sdf.parse(input);
    java.text.SimpleDateFormat sdf2 = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss", locale);
    String output = sdf2.format(date);
    System.out.println("input: " + input + "\noutput: " + output);
}
catch (java.text.ParseException e)
{
    // error handling goes here
    e.printStackTrace();
}