Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mySQL convert varchar to date

Tags:

mysql

I need to convert a varchar value of 1/9/2011 to a date in mySQL and I want only the month and year. So that I can then use the PERIOD_DIFF function (so I would need the above to be converted to 201101).

I've tried various ways using the STR_TO_DATE function:

SELECT STR_TO_DATE(CYOApp_oilChangedDate, '%m/%Y') FROM CYO_AppInfo

But I get weird results... (for example: 2009-01-00)

What am I doing incorrectly?

like image 219
webdad3 Avatar asked Jan 16 '11 15:01

webdad3


People also ask

How can get date in dd mm yyyy format in MySQL?

MySQL DATE_FORMAT() Function The DATE_FORMAT() function formats a date as specified.

Can we store date in VARCHAR in MySQL?

There is nothing stopping you putting non-date data in the VARCHAR column in the database. The VARCHAR version is culture specific. You can't easily sort the dates. It is difficult to change the format if you want to later.


2 Answers

select date_format(str_to_date('31/12/2010', '%d/%m/%Y'), '%Y%m');  

or

select date_format(str_to_date('12/31/2011', '%m/%d/%Y'), '%Y%m');  

hard to tell from your example

like image 55
Jon Black Avatar answered Sep 21 '22 18:09

Jon Black


As gratitude to the timely help I got from here - a minor update to above.

$query = "UPDATE `db`.`table` SET `fieldname`=  str_to_date(  fieldname, '%d/%m/%Y')";
like image 24
mbkhan Avatar answered Sep 19 '22 18:09

mbkhan