• Dan Guzman - Not the MVP (10/27/2010)


    So, is this the simplest and quickest way to get the last day of any month?

    DATEADD(MONTH,x,'2010-Jan-01')

    Where x is the month you are looking for the last day.

    I've seen a lot of code over the years that performs some sort of find the first day of the month after the month in question, then subtract 1 day. Seems totally unnecessary with this function.

    Not sure if you mis-typed that, but it is fairly obvious that will return the FIRST day of the month AFTER x. For example, if x=10, it will return 2010-11-01 00:00:00.000.

    This is the standard and most efficient way of getting the last day of the month a particular date is in:

    select LastDay = dateadd(mm,datediff(mm,-1,getdate()),-1)

    Result:

    LastDay

    -----------------------

    2010-10-31 00:00:00.000