Question

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.

Was it helpful?

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.

OTHER TIPS

To be explicit, this is basically what you want in SQL:

SELECT *
FROM `events` 
WHERE `Date Of Event` >= str_to_date('"+firstDate+"', '%m/%d/%Y') AND
      `Date Of Event` <= str_to_date('"+secondDate+"', %m/%d/%Y)"'

You can also do this conversion at the application level. Just be sure that you pass in the date constants in the "YYYY-MM-DD" format. Doing it in the database ensures that the comparisons really do work on dates.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top