Forum Moderators: coopster
In my DB there are date entries which have been manually entered for example, Jan 10th - 14th 2005, Mar 5th - 9th 2005 etc etc, Now i have been trying to come up with a way so that when chosen to sort by date it will query the DB and print them in order of date. Can someone point me in the right direction here please as all the methods i am trying dont seem to be working :(
TIA
Smad
If that is not a possibility then I would recomend writing a php script that will grab the data from db and then order them.
Build an array will all your db information in it. You should parse the dates as they come (change them to a good format) in to be in and then write a script to insert these dates back into either a new db or the origional. ( this would be a script to convert your "bad" dates to good ones, making it easy to search your db).
Your date field in your database should be in "timestamp" format, that is "yyyy-mm-dd hh:mm:ss". The value by default is "0000-00-00 00:00:00"
You need to write a php script that change your month (Jan, Feb, etc...) in digit format.
To create the timestamp, you should use something like:
$timestamp = "".$year."-".$digit_month."-".$day." ".$hour.":".$minute.":".$second."";
*************
Now if you date is coming from a form and data are immediatly placed in your database after clicking the submit button, then it is very easy, just set now() as default value in your date field. Your timestamp will be automatically added to your db.
datetype column. Most databases have lots of nice built-in functions as well as the standards that allow date manipulation, but only when the column is stored as type
date.
Second, you can SELECT the date in one format, but sort it in another.
SELECT
DATE_FORMAT(mydate, '%d %m %Y') AS formatted_date
FROM table
ORDER BY DATE_FORMAT(mydate, '%Y %m %d') DESC
;
However, you won't need to do this if you store the column as type
dateas described earlier:
SELECT
DATE_FORMAT(mydate, '%d %m %Y') AS formatted_date
FROM table
ORDER BY mydate DESC
;
Thanks
As said above, if data are immediatly inserted in your database after submitting the form, use the now() statement to put the current date in the db in a timestamp format.
Otherwise, use PHP to generate you date. Javascript is old fashion and a client-side script to get a date is a bad idea (what is Javascript is disable?).
You could modify the script on the javascript side to pass the date in the format you want. Otherwise, you can put it together on the server-side using substr() functions.
$date = '07042004'; // example incoming date
$month = substr ($date,0,2);
$day = substr ($date,2,2);
$year = substr ($date,4,4);
$newdate = $year.$month.$day;