Blog Post

SQL BLOG: Playing with Date Time

,

Below code returns remaining days in the month based on the input date. We can have this inside a function also which will return the integer value.

/* code starts here */

/* calculate remaining days in the month from the given input */
declare @tdate datetime
set @tdate = '2011-02-10'
select (CAST(DATEPART(DD,@tdate) as varchar(4))+'-'+CAST(DATEPART(MM,@tdate) as varchar(4))+'-'+CAST(DATEPART(YYYY,@tdate) as varchar(4))) As Today
,case when DATEPART(MM,@tdate) in (1,3,5,7,8,10,12)
     then (31-DATEPART(DD,@tdate))
     when DATEPART(MM,@tdate) in (4,6,9,11)
     then (30-DATEPART(DD,@tdate))
     when (DATEPART(MM,@tdate) = 2) and ((DATEPART(YYYY,@tdate) % 4) = 0)
     then (29-DATEPART(DD,@tdate))
     else  (28-DATEPART(DD,@tdate))
     end as Month_Remaining_Days

Run the above code in the query editor. Sample output is:

Today                       Months_Remaining_Days
2011-02-10               18

Rate

You rated this post out of 5. Change rating

Share

Share

Rate

You rated this post out of 5. Change rating