31

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?

3 Answers 3

79
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

Sign up to request clarification or add additional context in comments.

1 Comment

this is perfect solution for string to date
4

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')"; 

Comments

-1
select substring_index(your_column_name, '/', 1) years, substring_index(your_column_name, '/', -1) months, substring_index(substring_index(your_column_name, '/', 2),'/', -1) as dates from your_Table_Name; 

Then just concat everything and you will have a proper set to work around with.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.