Saturday, February 25, 2012

Defaulting Start and End dates to the previous month.

I have two parameters in my report (StartDate and EndDate). I want to default these parameters to the previous month.

For example... If today is 5/17/2007, I want StartDate to be 4/1/2007 and EndDate to be 4/30/2007. If today would be January 30th 2007, I would want StartDate to be 12/1/2006 and EndDate to be 12/31/2006.

How can I do this?

Nevermind... I used the following two functions. However, if you know of a better way to do this, please let me know.

Public Function EndDt() As Date

Dim Today As Date = Date.Today

Dim Day As Integer = Today.Day

Dim EndDate As Date

EndDate = Today.AddMonths(1)

EndDate = Today.AddDays(-Day)

Return EndDate

End Function

Public Function StartDt() As Date

Dim Today As Date = Date.Today

Dim Day As Integer = Today.Day - 1

Dim StartDate As Date

StartDate = Today.AddMonths(-1)

StartDate = Today.AddDays(-Day)

Return StartDate

End Function

|||

I can't think of a quick direct way

but I do want to suggest using BETWEEN, and first of month (so that you don't have to worry about # of days in a month)

e.g. for 05/17/2007

you'd want SQL code to be

Code Snippet

column BETWEEN 04/01/2007 AND 05/01/2007

since BETWEEN is inclusive, but only up to '05/01/2007 00:00:00', anything after 05/01/2007 midnight will NOT show up

so in backend SQL

it'll be like

Code Snippet

SELECT
previous_month = CAST( MONTH(getdate())-1 AS varchar) + '/01/' + CAST(YEAR(getdate()) AS varchar)
, current_month = CAST( MONTH(getdate()) AS varchar) + '/01/' + CAST(YEAR(getdate()) AS varchar)

then you get

previous_month current_month

4/01/2007 5/01/2007

No comments:

Post a Comment