Question

But I cannot Format it? Date is saved currently in the database under a 'text' type structure and saved a '1/1/2000'. I'm trying to pull this info out of the database and DATE_FORMAT it to '01/01/2000' (2 digit day & month) but it's showing all dates as 12/31/1969? Here's the query i'm using:

        $query = "SELECT Event_Title, Event_Details, Event_Time, Event_ID, DATE_FORMAT(Start_Date, '%m/%d/%Y') FROM tevents ORDER by Start_Date DESC"; 

Is there something wrong with my query?

database:

Rows    Start_Date Ascending
1   04/30/2014
1   05/03/2014
1   05/1/2014
1   05/3/2014
3   5/1/2014
1   5/15/2014
1   5/2/2014
2   5/20/2014
1   5/23/2014
1   5/24/2014
5   5/3/2014
3   5/6/2014
1   6/21/2014
1   6/23/2014
1   6/24/2014
1   6/25/2014
1   6/26/2014
1   6/27/2014
1   6/28/2014
1   6/5/2014
1   6/6/2014
Was it helpful?

Solution

Date stored as varchar or TEXT makes life miserable so better to store as date or datetime data type.

In your case you need to use str_to_date() for conversion before doing any format

$query = "SELECT 
Event_Title, 
Event_Details, 
Event_Time,
Event_ID, 
date_format(str_to_date(Start_Date,'%m/%d/%Y'),'%m/%d/%Y') as Start_Date
FROM tevents 
ORDER by date_format(str_to_date(Start_Date,'%m/%d/%Y'),'%Y-%m-%d') DESC";  

If its just for ordering then no need to do the

date_format(str_to_date(Start_Date,'%m/%d/%Y'),'%m/%d/%Y') as Start_Date

You can directly select since its converting to the same format, for ordering its needed.

OTHER TIPS

If you put a question into a closed envelope and give it to the neighbour, why can't he answer you?

'Text' means 'do not bother about the contents' for MySQL, it normally does not care about the content. If you use a DATE datatype, things get much easier at reading (and sorting works, and ranges, and where-clauses...) and a bit difficult on writing - you should format the dates into the form '2014-05-01' in the program code.

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