Get number of days in a month

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • rsrinivasan
    New Member
    • Mar 2007
    • 221

    Get number of days in a month

    Hi all,

    Is SQLSERVER have any built in function to get number of days for a given month?

    Thanks,
  • deepuv04
    Recognized Expert New Member
    • Nov 2007
    • 227

    #2
    Originally posted by rsrinivasan
    Hi all,

    Is SQLSERVER have any built in function to get number of days for a given month?

    Thanks,
    use the following query to get number of days in a given month
    [code=sql]
    declare @Date datetime
    select @Date = Getdate()

    select datepart(dd,dat eadd(dd,-1,dateadd(mm,1, cast(cast(year( @Date) as varchar)+
    '-'+cast(month(@D ate) as varchar)+'-01' as datetime))))
    [/code]

    my logic is i am taking the year and month of the given date and adding 1 to the month, then append 01 at the end so that we are moving to the 1 st of the next month. from the result i am moving one day back which is last day of the given month. if we take the day part from the final value which is number of days in a given month

    Comment

    • ck9663
      Recognized Expert Specialist
      • Jun 2007
      • 2878

      #3
      Here's another one:

      Code:
      DECLARE @dtDate DATETIME
          SET @dtDate = getdate()
      SELECT DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,@dtDate)+1,0))
      -- CK

      Comment

      Working...