Give me an algorithm to calculate the last day of the current month assuming that your language has functions to both create dates and perform date arithmetic.
A simple way to do this is to find the first day of the next month, and subtract a day. T-SQL does not have a last day of the month function so I found that I was having to write code like this a lot:
declare @startDate dateTime declare @endDate dateTime set @startDate = getDate() set @startDate = CAST(CAST(YEAR(@startDate) AS VARCHAR(4)) + '/' + CAST(MONTH(@startDate) AS VARCHAR(2)) + '/01' AS DATETIME) set @endDate = DATEADD(month, +1, @startDate) set @endDate = DATEADD(day, -1, @endDate) print @startDate print @endDateBut in reading Itzik Ben-Gan's book T-SQL Fundamentals, he illustrated a simpler way to to this:
DECLARE @StartDate datetime DECLARE @EndDate datetime SET @StartDate = DATEADD(month, DATEDIFF(month,'20120101', CURRENT_TIMESTAMP), '20120101') SET @EndDate = DATEADD(month, DATEDIFF(month,'20120131', CURRENT_TIMESTAMP), '20120131') print @startDate print @EndDateThis way simply calculates the month offset between an anchor date and the current date and then adds that many months back to the anchor date. If the anchor date is the first date of its month, this yields the first date of the current month. However if the anchor date is the last day of its month, you get the last day of the current month.
For me a much more elegant algorithm that is readable and maintainable.
No comments:
Post a Comment