views:

366

answers:

4

How to use DATEDIFF? How can I make this to work? or should I use DATEDIFF completly differently?

SELECT DATEDIFF('Started ','will_end') AS 'Duration' FROM my_table WHERE id = '110';

I try to get answer, how many days are inside of two dates.

I would like to get an aswer like:
Duration = 7 days;

I have this kind of database:

Started | will_end
2009-12-17 | 2009-12-24
2009-12-12 | 2009-12-26

+4  A: 

Put will_end first, started second:

SELECT  DATEDIFF('2009-12-24', '2009-12-17') 

---
  7

Also, remove the single quotes from your field names:

SELECT  DATEDIFF(will_end, started) AS Duration
FROM    my_table
WHERE   id = 110

, or replace them with the backticks:

SELECT  DATEDIFF(`will_end`, `started`) AS `Duration`
FROM    `my_table`
WHERE   `id` = 110
Quassnoi
http://dev.mysql.com/doc/refman/5.1/en/date-and-time-functions.html#function_datediff
Jonathan Sampson
Thank you! very good examples!
jsk
A: 

replace the order

DATEDIFF('will_end','Started')

Haim Evgi
A: 

I think there are 3 parameter to be passed in DATEDIFF ( datepart , startdate , enddate )

so your code would be DATEDIFF ( dd , 'Started ','will_end' )

http://msdn.microsoft.com/en-us/library/ms189794.aspx

Mark O'Grady
The question is about `MySQL`
Quassnoi
Er... what's this got to do with MYSQL?
ILMV
+2  A: 

Are you getting a NULL result? You have the column names in single quotes in your query, which means you are passing the strings 'Started ' and 'will_end' to DATEDIFF rather than the column values. Try removing the single quotes, and you will start to see some results:

SELECT DATEDIFF(Started, will_end) AS Duration FROM my_table WHERE id = '110';

Note that this will give you a negative result. To get a positive result, reverse the order of the columns:

SELECT DATEDIFF(will_end, Started) AS Duration FROM my_table WHERE id = '110';
Phil Ross