Search code examples
mysqlsqldatejcalendar

Converting Date format to run select statement


For a program I am writing (In Java) for school I have to run a select statement between to dates to produce a timetable. This selects data from SQL and puts it into a table. My problem is that the data type date is in the format 'YYYY-MM-DD' and the JCalendar library I am using gives the date as MM/DD/YYYY, so this breaks it. Is there anyway of changing the SQL Format? Or an easy way to fix this?

This is my select query:

'"SELECT * FROM `events` 
 WHERE `Date Of Event` >= '"+firstDate+"' AND `Date Of Event` <= '"+secondDate+"'"' 

where first and last date are in a different format.

Any help is greatly appreciated.


Solution

  • You could use the SimpleDateFormat class to parse the date into a Date object and use another SimpleDateFormat object to parse it into the required format.

    Here's an example of how to do it:

    String sqlDate = "1992-02-16";
    SimpleDateFormat sdfInput = new SimpleDateFormat("yyyy-MM-dd");
    Date date = sdfInput.parse(sqlDate);
    SimpleDateFormat sdfResult = new SimpleDateFormat("MM-dd-yyyy");
    String result = sdfResult.format(date);
    

    The reason why the database is storing it in yyyy-MM-dd format is to allow sorting, while your JCalendar uses MM-dd-yyyy format because it is the standard American way of displaying a date.

    I also strongly recommend you use a PreparedStatement and add the parameters to it rather than concatenating.