Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does the Datediff function show different values?

Tags:

When I am executing following query I am getting different results.

SELECT Datediff(year, 0, Getdate()); 

The result was 115

When I use this, I am getting another result:

SELECT Datediff(year, 1900, Getdate()); 

The result was 110

Actually in SQL Server it will take from 1900-01-01, but why do these show different values?

like image 874
Sai Praveen Avatar asked Jun 30 '15 07:06

Sai Praveen


People also ask

How does the datediff function work?

The DATEDIFF() function returns an integer value that represents the difference between the start date and end date, with the date part as the unit. If the result is out of range for the integer (-2,147,483,647), the DATEDIFF() function returns an error. Here, the DATEDIFF BIG() function should be used instead.

What does a datediff function return?

DateDiff Query examples Returns the difference between Date2 and Date1 (consider Date1 as oldest and Date2 as newest) as number of 'Years'.

What are the three parameters of datediff function?

This function accepts three parameters namely interval, first value of date, and second value of date.

Does datediff give absolute value?

It finds the difference in dates, and then takes the absolute value. The absolute value would be 0 to 365 for all datediff values from -365 to +365.


2 Answers

Try this to explain the logic:

select cast(0 as datetime) select cast(1 as datetime) 

An integer is interpreted as the number of Days since 1900-01-01 whereas a string value such as '1900' will be interpreted as a date format.

1900 Days from Jan 1st 1900 is 1905-03-16, which is five years from 1900 and 110 years from now (2015).

like image 96
SAS Avatar answered Sep 28 '22 08:09

SAS


This is because if you cast 0 as datetime, it returns 1900 as the year part, whereas 1900 cast as datetime returns 1905 as the year part.

Demo

From MSDN:

Values with the datetime data type are stored internally by Microsoft SQL Server as two 4-byte integers. The first 4 bytes store the number of days before or after the base date, January 1, 1900. The base date is the system reference date.

That means, casting the literal 0 to datetime is equivalent to getting the datetime value for 0 days after 1/1/1900, which is 1/1/1900. Similarly for 1900. Therefore, as @MartinSmith points out in the comments, your calculation is equivalent to SELECT Datediff(year,dateadd(d,0,'1/1/1900'), Getdate()) which returns 115 as expected.

Possibly worth noting that the MSDN page on Cast and Convert does not specifically cover this scenario i.e. int to datetime.

like image 37
shree.pat18 Avatar answered Sep 28 '22 08:09

shree.pat18