Question

Is it possible to change from a Varchar to Date format in Mysql but with a day name ie

Current Date format Monday 16th September 2013

I actually like to have the day 'Monday' included but my issue seems to be ordering by date actually orders alphabetically so would like to convert to Date format if possible.

Thank you

Was it helpful?

Solution

Like eggyal says,

  SELECT STR_TO_DATE('Monday 16th September 2013','%W %D %M %Y')

does the job for the date layout you specify.

This will also work for a column containing dates. For example, if you have these dates in a column:

what_day
Monday 16th September 2013
Tuesday 17th September 2013
Thursday 19th September 2013
Friday 20th September 2013
Saturday 21st September 2013
Thursday 19th September 2013

You can do

 SELECT what_day
   FROM days
  ORDER BY STR_TO_DATE(what_day,'%W %D %M %Y')

to get the days in date order. See this: http://sqlfiddle.com/#!2/74c58/1/0

Beware, MySQL isn't checking your dates for much validity. It ignores the day of the week. And, if you put in 31st September 2013 (not a valid date) MySQL thinks, reasonably, that you mean 1st October, 2013.

This makes it possible to do all kinds of nice date arithmetic like

SELECT STR_TO_DATE('Monday 16th September 2013','%W %D %M %Y') 
       - INTERVAL 1 QUARTER

It also allows proper sorting.

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