Reputation: 126
Why does the following query in MySQL result in a null for that timestampdiff()?
SELECT EndDate, /* EndDate is YEAR(4) datatype with value 2013 */
year('2015-01-01') a,
timestampdiff( YEAR, Year('2015-01-01'), EndDate) b
FROM table
Results:
EndDate a b
2013 2015 NULL
Upvotes: 2
Views: 4257
Reputation: 126
MySQL doesn't automatically convert YEAR(4) datatypes to DATETIME. I fixed it by appending a month/day to EndDate and it sees it as a DATETIME.
SELECT EndDate,
timestampdiff(YEAR, STR_TO_DATE('2015-01-01','%Y-%m-%d'), CONCAT(EndDate,'-01-01')) d
FROM table
Thanks to @Uueerdo for identifying the problem.
Upvotes: 0
Reputation: 5326
timestampdiff()
requires valid dates for the second and third argument. YEAR('2015-01-01')
returns 2015
, which is not a valid date, which breaks timestampdiff()
causing it to return NULL. Just make the second argument '2015-01-01'
and as long as your EndDate
is good, it should work.
Upvotes: 2
Reputation: 133370
Try convert the year a stingr to a valid date
SELECT EndDate, /* EndDate is YEAR(4) datatype with value 2013 */
STR_TO_DATE('2015-01-01','%Y-%m-%d') a,
timestampdiff( YEAR, STR_TO_DATE('2015-01-01','%Y-%m-%d'), EndDate) b
FROM table
Upvotes: 0