开发者

Java Format Custom Date to MySQL DATETIME

I have a String with a value in the format: 01-Jul-2011 12:52:00 .

I would like to format this to be inserted into a MySQL database with the type as DATETIME.

I realise that I need to get it in the form 01-07-2011 12:52:00 but I can't figure out how to开发者_开发技巧 do this.

Any solutions?


@Jigar is correct, if not terse. But it looks like you might need more info, and I'm going to spoonfeed it to you.

Firstly, you shouldn't be trying to format a date to suit mysql. You should be passing a Date as a parameter to your sql query (not building up a String of sql).

To parse the date from your input, try code like this:

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"
}

Here's an example of how you make sql calls using a JDBC connector passing parameters:

Date date = format.parse(input);
jdbcConnection.createStatement().execute("insert into mytable (id, some_date) values (?, ?)", new Object[]{1, date});

You don't need to worry about how to format the date for mysql - let the JDBC driver do that for you.


SimpleDateFormat


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();
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜