Find Number of Days for a Given Date

Posted: May 15, 2011 in SQL Server 2005

To find the number of days for any given date, run the follwing script:

-- Declare variables
DECLARE @ldt_date DATETIME;

-- Initialise variables
SET @ldt_date = GETDATE();

SELECT CASE WHEN MONTH(@ldt_date) IN (1, 3, 5, 7, 8, 10, 12) THEN 31
            WHEN MONTH(@ldt_date) IN (4, 6, 9, 11) THEN 30
            ELSE 
               CASE WHEN (    YEAR(@ldt_date) % 4    = 0
                          AND YEAR(@ldt_date) % 100 != 0) 
                          OR (YEAR(@ldt_date) % 400  = 0) THEN 29
                    ELSE 28
               END
       END no_of_days;
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s