Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simplest way to create a date that is the first day of the month, given another date

In SQL Server what is the simplest/cleanest way to make a datetime representing the first of the month based on another datetime? eg I have a variable or column with 3-Mar-2005 14:23 and I want to get 1-Mar-2005 00:00 (as a datetime, not as varchar)

like image 815
Rory Avatar asked Sep 23 '08 15:09

Rory


1 Answers

Select DateAdd(Month, DateDiff(Month, 0, GetDate()), 0)

To run this on a column, replace GetDate() with your column name.

The trick to this code is with DateDiff. DateDiff returns an integer. The second parameter (the 0) represents the 0 date in SQL Server, which is Jan 1, 1900. So, the datediff calculates the integer number of months since Jan 1, 1900, then adds that number of months to Jan 1, 1900. The net effect is removing the day (and time) portion of a datetime value.

like image 56
George Mastros Avatar answered Sep 29 '22 10:09

George Mastros