3

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?

3 Answers 3

4

@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.

Sign up to request clarification or add additional context in comments.

Comments

1

SimpleDateFormat

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.