Find First Day of Month, Last Day of Month, etc

Today I was writing some code where I needed to calculate the end of the month for a certain date.  As per usual, I Googled, and found various examples, some using old VB functions, some using methods of the Date object,  some very involved and using lots of string manipulation and converting of things from dates to strings and back again, etc.  I used these various examples to develop a little utility class, which is as follows:

Public Class UtilityDates

Public Shared Function GetFirstOfMonth() As Date
Return GetFirstOfMonth(DateTime.Today)
End Function

Public Shared Function GetFirstOfNextMonth() As Date
Return GetFirstOfNextMonth(DateTime.Today)
End Function

Public Shared Function GetEndOfMonth() As Date
Return GetEndOfMonth(DateTime.Today)
End Function

Public Shared Function GetEndOfLastMonth() As Date
Return GetEndOfLastMonth(DateTime.Today)
End Function

Public Shared Function GetFirstOfMonth(ByVal startDate As Date) As Date
‘remove all but one day from date to get first of month
Return startDate.AddDays(-(startDate.Day – 1))
End Function

Public Shared Function GetFirstOfNextMonth(ByVal startDate As Date) As Date
‘get first of month and then add one month
Return GetFirstOfMonth(startDate).AddMonths(1)
End Function

Public Shared Function GetEndOfMonth(ByVal startDate As Date) As Date
‘subtract one day from first of last month
Return GetFirstOfNextMonth(startDate).AddDays(-1)
End Function

Public Shared Function GetEndOfLastMonth(ByVal startDate As Date) As Date
‘subtract one day from first of the month
Return GetFirstOfMonth(startDate).AddDays(-1)
End Function

End Class

Note that each method is overloaded, so you can calculate from the default of today’s date, or send in a specific date.  Of course, you could add a few more functions from here, but I thought that this was plenty for today:)

Advertisements