MySQL – Calculate Datediff Between Two Dates by Year

MySQL

I have two dates date column like '2017-12-29' and '2018-01-05' the datediff between these dates is 8, but i want to know the datediff which fall on 2018 which should be 5. I'm working on mysql.

Best Answer

If I'm understanding correct, you need only the days from the year of your second date. Based in the answer from dbdemon, you could use a CASE:

CREATE TABLE t1 (
  id int unsigned primary key, 
  date1 date, 
  date2 date
);

INSERT INTO t1 (id, date1, date2) 
  VALUES (1, '2017-12-29', '2018-01-05'),
  (2, '2018-02-20', '2018-03-05');

SELECT 
  date1,
  date2,
  DATEDIFF(date2,CASE YEAR(date1) WHEN YEAR(date2) THEN date1 ELSE MAKEDATE(YEAR(date2),1) END) 
FROM t1;

That way, if the dates are from the same year, the difference will be the same, if there from different year it'll count only starting from first day of the year.