tags:

views:

37

answers:

2

I am currently pulling three form field inputs off the request object. The day, the month, and the year.

Day would be 11 for 11th day of the month Month would be 12 for december Year would be 2010 representing this year.

I need to convert this into a Java Date object, but since so much has been changed, I am not sure what the best way to store this in a java object. I need it in the format

YYYY-MM-DD HH:MM:SS
so I can compare to dates in the MySql Database.

+2  A: 

SimpleDateFormat can convert strings to java.util.Date objects. Date class has a getTime() method that yields the date in unix time format (number of milliseconds since January 1, 1970, 00:00:00 GMT).

SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd kk:mm:ss");
long unix_time = dateFormat.parse(date).getTime();

You can use UNIX_TIMESTAMP() in MySQL to convert to unix time as well.

mysql> SELECT UNIX_TIMESTAMP('2007-11-30 10:30:19');
        -> 1196440219
Bakkal
+1  A: 

I need to convert this into a Java Date object

Instantiate a GregorianCalendar, set the appropriate fields, and call getTime on it. Since it doesn't sound like you're collecting time information, you'll probably want to specifically clear those fields or you'll get the current time of when that object was constructed.

I need it in the format [...] so I can compare to dates in the MySql Database.

You shouldn't need it in a text format to compare dates. Create the column using the database's native date/time type and use the Date type within Java. JDBC should do the conversion for you as it goes in or out of the database.

Date formatting should only be used for output to an external process or for display. See Bakkal's answer for formatting using SimpleDateFormat.

Alan Krueger