mysql extract year from date format
MysqlMysql Problem Overview
I need a mysql query to extract the year from the following date format from a table in my database.
For eg :
subdateshow
----------------
01/17/2009
01/17/2009
01/17/2009
01/17/2009
01/17/2009
the following query didn't working
select YEAR ( subdateshow ) from table
The column type is varchar. Is there any way to solve this?
Mysql Solutions
Solution 1 - Mysql
Since your subdateshow is a VARCHAR column instead of the proper DATE, TIMESTAMP or DATETIME column you have to convert the string to date before you can use YEAR on it:
SELECT YEAR(STR_TO_DATE(subdateshow, "%m/%d/%Y")) from table
See http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_str-to-date
Solution 2 - Mysql
SELECT EXTRACT(YEAR FROM subdateshow) FROM tbl_name;
Solution 3 - Mysql
You can try this:
SELECT EXTRACT(YEAR FROM field) FROM table WHERE id=1
Solution 4 - Mysql
This should work:
SELECT YEAR(STR_TO_DATE(subdateshow, '%m/%d/%Y')) FROM table;
eg:
SELECT YEAR(STR_TO_DATE('01/17/2009', '%m/%d/%Y')); /* shows "2009" */
Solution 5 - Mysql
try this code:
SELECT DATE_FORMAT(FROM_UNIXTIME(field), '%Y') FROM table
Solution 6 - Mysql
This should work if the date format is consistent:
select SUBSTRING_INDEX( subdateshow,"/",-1 ) from table
Solution 7 - Mysql
TRY:
SELECT EXTRACT(YEAR FROM (STR_TO_DATE(subdateshow, '%d/%m/%Y')));
Solution 8 - Mysql
try this code:
SELECT YEAR( str_to_date( subdateshow, '%m/%d/%Y' ) ) AS Mydate