Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations wOOdy-Soft on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

First and Last days of a given month function

Status
Not open for further replies.

Axoliien

Programmer
Aug 19, 2003
166
US
The following functions programmed in VB are made to give the first or the last day of a given month (passed in as a date). After looking and trying some examples in the forums, I could not get any to work correctly since they would error either when on the first or last day of the month. I hope this helps, and though it may be a bit heavy on overhead, it seems to work well for the dates I am working with. The first function finds the first day of the month in the given date. The second function finds the last day of the month in the given date by calling the first function. The third function finds the last day of the month in the given date without a call to the first function. They are all included for anyone who wants the options. Note: The functions are long so lines may be cut from site formatting.

[tt]
Public Function FirstDayOfMonth(ByVal sdate As Date) As Date
FirstDayOfMonth = (DatePart("m", sdate) & "/01/" & DatePart("yyyy", sdate))
End Function

Public Function LastDayOfMonth(ByVal sdate As Date) As Date
LastDayOfMonth = DateAdd("m", 1, FirstDayOfMonth(sdate)) - 1
End Function

Public Function LastDayOfMonthInd(ByVal sdate As Date) As Date
LastDayOfMonth = DateAdd("m", 1, FirstDayOfMonth(sdate)) - 1
End Function
[/tt]

 
OK ... but the "LastDayOfMonthInd" function doesn't set the value of the function name and it appears to do exactly the same thing as "LastDayOfMonth" (i.e. it does call the "FirstDayOfMonth" Function.)
 
Wow, I can't believe I made that mistake, no excuses. No edit here? Here is a remake, should be easy enough to understand now...

[tt]
Public Function FirstDayOfMonth(ByVal sdate As Date) As Date
FirstDayOfMonth = (DatePart("m", sdate) & "/01/" & DatePart("yyyy", sdate))
End Function

Public Function LastDayOfMonth(ByVal sdate As Date) As Date
LastDayOfMonth = DateAdd("m", 1, FirstDayOfMonth(sdate)) - 1
End Function

Public Function LastDayOfMonthInd(ByVal sdate As Date) As Date
LastDayOfMonthInd = DateAdd("m", 1, (DatePart("m", sdate) & "/01/" & DatePart("yyyy", sdate))) - 1
End Function
[/tt]
 
The DateSerial function is set up to do this as well

DateSerial(Year(sdate),Month(sdate),1)

returns the 1st day of the month

DateSerial(Year(sdate),Month(sdate)+ 1,0)

returns the last day of the month

DateSerial(Year(sdate),Month(sdate)+ 1,1)

gets you the first day of next month.
There are lots of ways to configure this function.

Paul

 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top