Get the last day of the month in SQL

后端 未结 20 2031
借酒劲吻你
借酒劲吻你 2020-11-27 04:49

I need to get the last day of the month given as a date in SQL. If I have the first day of the month, I can do something like this:

DATEADD(DAY, DATEADD(MONT         


        
相关标签:
20条回答
  • 2020-11-27 05:08

    Works in SQL server

    Declare @GivenDate datetime
    SET @GivenDate = GETDATE()
    
    Select DATEADD(MM,DATEDIFF(MM, 0, @GivenDate),0) --First day of the month 
    
    Select DATEADD(MM,DATEDIFF(MM, -1, @GivenDate),-1) --Last day of the month
    
    0 讨论(0)
  • 2020-11-27 05:08

    Just extend your formula out a little bit:

    dateadd(day, -1,
        dateadd(month, 1,
            cast(month('5/15/2009') as varchar(2)) + 
            '/1/' + 
            cast(year('5/15/2009') as varchar(4)))
    
    0 讨论(0)
  • 2020-11-27 05:09

    WinSQL to get last day of last month (i.e today is 2017-02-09, returns 2017-01-31: Select dateadd(day,-day(today()),today())

    0 讨论(0)
  • 2020-11-27 05:13

    I wrote following function, it works.

    It returns datetime data type. Zero hour, minute, second, miliseconds.

    CREATE Function [dbo].[fn_GetLastDate]
    (
        @date datetime
    )
    returns datetime
    as
    begin
    
    declare @result datetime
    
     select @result = CHOOSE(month(@date),  
     DATEADD(DAY, 31 -day(@date), @date),
     IIF(YEAR(@date) % 4 = 0, DATEADD(DAY, 29 -day(@date), @date), DATEADD(DAY, 28 -day(@date), @date)), 
     DATEADD(DAY, 31 -day(@date), @date) ,
     DATEADD(DAY, 30 -day(@date), @date), 
     DATEADD(DAY, 31 -day(@date), @date),
     DATEADD(DAY, 30 -day(@date), @date), 
     DATEADD(DAY, 31 -day(@date), @date),
     DATEADD(DAY, 31 -day(@date), @date),
     DATEADD(DAY, 30 -day(@date), @date),
     DATEADD(DAY, 31 -day(@date), @date),
     DATEADD(DAY, 30 -day(@date), @date), 
     DATEADD(DAY, 31 -day(@date), @date))
    
     return convert(date, @result)
    
    end
    

    It's very easy to use. 2 example:

    select [dbo].[fn_GetLastDate]('2016-02-03 12:34:12')
    
    select [dbo].[fn_GetLastDate](GETDATE())
    
    0 讨论(0)
  • 2020-11-27 05:14

    Here's my version. No string manipulation or casting required, just one call each to the DATEADD, YEAR and MONTH functions:

    DECLARE @test DATETIME
    SET @test = GETDATE()  -- or any other date
    
    SELECT DATEADD(month, ((YEAR(@test) - 1900) * 12) + MONTH(@test), -1)
    
    0 讨论(0)
  • 2020-11-27 05:15

    I know this is a old question but here is another solution that works for me

    SET @dtDate = "your date"
    DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,@dtDate)+1,0))
    

    And if some one is looking for different examples here is a link http://blog.sqlauthority.com/2007/08/18/sql-server-find-last-day-of-any-month-current-previous-next/

    I hope this helps some one else. stackoverflow Rocks!!!!

    0 讨论(0)
提交回复
热议问题