Search code examples
sql-servert-sqldateadd

Query to get the first day of the month not working with DATEADD


I've been writing queries to truncate the time from a given datetime for years now, based on answers like this one and this one (and many other places), that groups a couple functions like

SELECT DATEADD(day, 0, DATEDIFF(day, 0, getdate()))

and it always gives the right answer.

I figured I could translate the same logic to finding the first of the current month by using month instead of day, but it's giving me a weird date for the result: 1903-10-17, instead of 2015-05-01.


Solution

  • My parameters have always been in the wrong order.

    It turns out the format for DATEADD I've been using all these years is wrong, and it's only been working because it's using the day datepart. Casting an int to a date increments the day:

    SELECT CAST(0 AS datetime) = '1900-01-01 00:00:00.000'
    SELECT CAST(1 AS datetime) = '1900-01-02 00:00:00.000'
    SELECT CAST(2 AS datetime) = '1900-01-03 00:00:00.000'
    

    I should be using DATEADD(d, DATEDIFF(d, 0, getdate()), 0) - the parameters are (datepart, number, date), as laid out here at MSDN.

    Writing it as SELECT DATEADD(month, DATEDIFF(month, 0, getdate()), 0) gives the expected result of 2015-05-01.