Site Search:
Sign in | Join | Help
4Penny.net

SQL Server (T-SQL)

Comments and notes on SQL Server 2000, 2005, and T-SQL

Datetime calculations

Here is a really nice datetime calc from the MAY 2007 edition of SQL Server Magazine (www.sqlmag.com). I reprint it here because it is too good to loose, and too long to remember perfectly.

If you are reading this and don't have a subscription to the magazine, this code alone is worth the subscription. Click on the link above and... just ... do... it <smiles>

 Itzik, you do good work, I love your column.

select dateadd(month,datediff(month,0,getdate()),0)

This will get the first day of the month of the passed in date (we use getdate() here). Quoting Itzik here:

The logic of this technique is a follows: Calculate the difference in terms of months between an anchor date at midnight (in this case, 0, represending the base date January 1, 1900) and the event date. Call this difference diff. Add diff months to the anchor date.

 

 

 

 

 

Comments

No Comments

About Steve Gray

Steve is a seasoned (translate: old) developer in VB and ASP.NET. He spends most of his time in Dynamics GP, writing custom mods for consulting firms. Crystal reports, eConnect, VS Tools for Dynamics... anything that comes along.