views:

334

answers:

2

I'm looking for an easy way to generate a MySQL DATETIME from any type of time input a user may enter. PHP makes it easy with its strtotime() function that can do:

strtotime(’2004-02-12T15:19:21+00:00′);

strtotime(’Thu, 21 Dec 2000 16:01:07 +0200′);

strtotime(’Monday, January 1st’);

strtotime(’tomorrow’);

strtotime(’-1 week 2 days 4 hours 2 seconds’);

Outputs:

2004-02-12 07:02:21

2000-12-21 06:12:07

2009-01-01 12:01:00

2009-02-12 12:02:00

2009-02-06 09:02:41

I want this in Java!

+1  A: 

You can't have this in Java - and that's a good thing, too :-)

What you can have is string-to-date conversion for which you specify an exact format:

SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Date date = sdf.parse("2009/08/03 18:13:47");

Note that if the String passed in can not be parsed using specified format you'll get a ParseException thrown from parse() method.

Documentation is here: java.text.SimpleDateFormat

ChssPly76
A: 

Thanks for the quick reply ChssPly76. Here's my solution, although it's hard coded to handle dates coming in this format: "5 Aug 2009 07:27:51 GMT". Perhaps there is a way to allow it to easily handle other formats in case of a parse exception?

public static String stringToDateTime(String string) {
    SimpleDateFormat sdf = new SimpleDateFormat("d MMM yyyy HH:mm:ss z");
    Date date;
    String sqlDate;
    try {
        date = sdf.parse(string);
        SimpleDateFormat sqlFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        sqlDate = sqlFormat.format(date);
    }
    catch(ParseException ex) {
        sqlDate = string;
    }

    return sqlDate;
}
Kirk
You could add all possible formats your users may enter to a list and iterate through it, attempting to parse and catching an exception until parse is successful or list ends. Note of caution: based on your code sample it looks like you're trying to convert date to a string MySQL expects in order to dynamically build a SQL statement? That's not a good approach, you should use a PreparedStatement instead and pass date parameter as Date object.
ChssPly76