How to find out if this is a leap year with MSSQL
According to wikipedia:
- The average year length of 365.2425 days.
- We add a 29th day to February every 4 years, almost.
Leap year algorithm
As per Wikipidia
if year modulo 400 is 0 then leap else if year modulo 100 is 0 then no_leap else if year modulo 4 is 0 then leap else no_leap
Meaning: 1896 was a leap year, and the next leap year was 1904. While the year 2000 was leap year, 2100 will not be a leap year. Leap years affect when calculating days, for aging.
Microsoft with SQL Server has already done all the work, so how do you know when this is a leap year or not. Now for some obvious observations:
- A leap year has 366 days.
- February has 29 days in a leap year.
- A non leap year has 365 days.
- February has 28 days in a non leap year.
Leap year calculation: alternative 1
Count the number of days for that year. If there are 365 days then it's not a leap year, if there are 366 days then it's a leap year.
Not a leap year
- SELECT CURRENT_TIMESTAMP AS 'today',
- CAST((STR( YEAR( CURRENT_TIMESTAMP ) ) + '/01/01') AS SMALLDATETIME) AS 'Current year',
- CAST((STR( YEAR( CURRENT_TIMESTAMP ) +1 ) + '/01/01') AS SMALLDATETIME) AS 'Next year',
- DATEDIFF(DAY,CAST((STR( YEAR( CURRENT_TIMESTAMP ) ) + '/01/01') AS SMALLDATETIME),CAST((STR( YEAR( CURRENT_TIMESTAMP ) +1 ) + '/01/01') AS SMALLDATETIME)) AS 'Non Leap year: Num of days';
- go
today Current year Next year Non Leap year: Num of days ----------------------- ----------------------- ----------------------- -------------------------- 2007-07-29 18:02:15.770 2007-01-01 00:00:00 2008-01-01 00:00:00 365 (1 row(s) affected)
Leap year
The year 2000 was a leap year.
- SELECT DATEDIFF(DAY,'2000/01/01','2001/01/01') AS 'Leap year: Num of days';
- go
Leap year: Num of days ---------------------- 366 (1 row(s) affected)
Leap year calculation: alternative 2
Count the number of days in February. If there are 28 days then it's not a leap year, if there are 29 days then it's a leap year.
Not a leap year
- SELECT DATEDIFF(DAY,CAST((STR( YEAR( CURRENT_TIMESTAMP ) ) + '/02/01') AS SMALLDATETIME),CAST((STR( YEAR( CURRENT_TIMESTAMP ) ) + '/03/01') AS SMALLDATETIME)) AS 'Non leap year: Num of days in February';
- go
Non leap year: Num of days in February -------------------------------------- 28 (1 row(s) affected)
Leap year
- SELECT DATEDIFF(DAY,CAST(('2000/02/01') AS SMALLDATETIME),CAST(('2000/03/01') AS SMALLDATETIME)) AS 'Leap year: Num of days in February 2000';
- go
Leap year: Num of days in February 2000 --------------------------------------- 29 (1 row(s) affected)

