Finding the first and last day of the month in VB.NET

This article describe an approach to find out the first and last day of the month based upon either a selected date or selected month.

 Introduction

This article shall describe a very simple approach to finding out the first and last day of the month based upon either a selected date or selected month. There are other ways to accomplish the task aside from what is presented in this article; however, this approach is reliable and quite easy to use and does not involve the typical approach of using time spans to resolve the question.

The use of such an approach may be of some value if, for example, one were writing an application that queries a database and the queries were to be bound to return result sets limited to a single month starting always with the first day of the month and ending with the last day of the month.

Naturally, resolving the first day of the month is not much of an issue; it is pretty safe to assume the first day of the month is going to be the first. However, I show calculating the first day of the month in a similar manner so as to permit the involved function to return a DateTime value in response to a request for the first day of the month. One could also obtain a DateTime value by taking the month and year from the current date and the either subtracting the appropriate number of days from the date to set it to the first or by creating a new DateTime variable and instancing it with the selected dates month and year along with manually setting the new date day to 1 as shown below.

Dim dt As New DateTime(dtpDate.Value.Year, dtpDate.Value.Month, 1)

The value of returning the date as a DateTime value would be apparent if one were required to perform some DateTime related functions on the returned value.




Figure 1: Finding the First and Last Days of a Month

Getting Started

The solution contains a single Windows Forms project called FirstLastDayVB which was written in VB.NET; the application contains a single Windows form (Form1.vb); this form contains all of the code necessary to calculate and display the first and last days of the month. That portion of the code used to determine the first and last days of the month could have just as easily been placed into a separate static class accessible by the main application form.


 

Figure 2:  Solution Explorer with the Project Visible

Code:  Main Form (Form1.vb)

This form class is used to demonstrate the use of the methods used to calculate and display the first and last days of the month. The form class is pretty simple and the annotation provided describes the purpose of each part of the class. The form itself, visible in Figure 1, contains a collection of controls used to set the input values used by the class methods, and to display the results to the user.

<summary>
Example of one approach to obtaining the first and last days of any given month

</summary>

<remarks>none</remarks>

Public Class Form1

 

The constructor is shown following the class declaration; it has been modified to load an array containing a list of all of the months into a ComboBox and to set the control to display the first item in its collection upon initialization.

 

#Region "Constructor"

<summary>

Constructor

</summary>

<remarks></remarks>

public Sub New()

This call is required by the Windows Form Designer.

InitializeComponent()

Add any initialization after the InitializeComponent() call.

Dim months() As String = {"January""February""March""April""May""June""July""August","September""October""November""December"}

populate a combobox with all of the months

cboMonths.Items.AddRange(months)

select an item

cboMonths.SelectedIndex = 0

End Sub

#End Region

 

The click event handlers region follows; this section actually calls the class methods used to retrieve the first and last of the month date values and in turn displays that information to the user. The annotation describes the code.

 

#Region "Click Event Handlers"

<summary>

Find and display the first and last day of the month for the supplied date

</summary>

<param name="sender"></param>

<param name="e"></param>

<remarks></remarks>

Private Sub btnFind_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) HandlesbtnFind.Click

set the calendar date and click the find button to report the first and last day of the month for any month selected in the date time picker control set first day

txtFirstDay.Text = GetFirstDayOfMonth(dtpDate.Value).ToShortDateString()

get day of week for first day

Dim dateParts() As String = txtFirstDay.Text.Split("/")

Dim dtFirstTemp As New DateTime(Convert.ToInt32(dateParts(2)), Convert.ToInt32(dateParts(0)), Convert.ToInt32(dateParts(1)))

display day of week in label

lblDowFirst1.Text = dtFirstTemp.DayOfWeek.ToString()
set last day
txtLastDay.Text = GetLastDayOfMonth(dtpDate.Value).ToShortDateString()
get day of week for last day

Dim dateParts2() As String = txtLastDay.Text.Split("/")

Dim dtLastTemp As New DateTime(Convert.ToInt32(dateParts2(2)), Convert.ToInt32(dateParts2(0)), Convert.ToInt32(dateParts2(1)))

display day of week in label

lblDowLast1.Text = dtLastTemp.DayOfWeek.ToString()

End Sub

<summary>

Execute the code to set the first and last day of the month by passing in only an integer representation of the month

</summary>

<param name="sender"></param>

<param name="e"></param>

<remarks></remarks>

Private Sub btnFind2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) HandlesbtnFind2.Click

set the calendar date and click the find button to report the first and last day of the month for any month selected in the date time picker control set first day

txtFirstDay2.Text = GetFirstDayOfMonth(cboMonths.SelectedIndex +1).ToShortDateString()

get day of week for first day

Dim dateParts() As String = txtFirstDay2.Text.Split("/")

Dim dtFirstTemp As New DateTime(Convert.ToInt32(dateParts(2)), Convert.ToInt32(dateParts(0)), Convert.ToInt32(dateParts(1)))

display day of week in label

lblDowFirst2.Text = dtFirstTemp.DayOfWeek.ToString()

set last day

txtLastDay2.Text = GetLastDayOfMonth(cboMonths.SelectedIndex + 1).ToShortDateString()

get day of week for last day

Dim dateParts2() As String = txtLastDay2.Text.Split("/")

Dim dtLastTemp As New DateTime(Convert.ToInt32(dateParts2(2)), Convert.ToInt32(dateParts2(0)), Convert.ToInt32(dateParts2(1)))

display day of week in label

lblDowLast2.Text = dtLastTemp.DayOfWeek.ToString()

End Sub

<summary>

Exit the application

</summary>

<param name="sender"></param>

<param name="e"></param>

<remarks></remarks>

Private Sub btnExit_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) HandlesbtnExit.Click

Application.Exit()

End Sub

#End Region

 

The last region in the class contains the methods used to get the first and last days of the month. The region provides four methods, one gets the first day of the month based upon receipt of a date, one gets the first day of the month based upon receipt of an integer value representing a month, one gets the last day of the month based upon receipt of a date, one gets the last day of the month based upon receipt of an integer value representing a month.  The annotation describes the process used in each method.


#Region "Private Methods"

<summary>

Get the first day of the month for any full date submitted

</summary>

<param name="dtDate"></param>

<returns></returns>

Private Function GetFirstDayOfMonth(ByVal dtDate As DateTime) As DateTime

set return value to the first day of the month for any date passed in to the method

create a datetime variable set to the passed in date

Dim dtFrom As DateTime = dtDate

remove all of the days in the month except the first day and set the variable to hold that date

dtFrom = dtFrom.AddDays(-(dtFrom.Day - 1))

return the first day of the month

Return dtFrom

End Function

<summary>

Get the first day of the month for a month passed by it's integer value

</summary>

<param name="iMonth"></param>

<returns></returns>

Private Function GetFirstDayOfMonth(ByVal iMonth As Int32) As DateTime

set return value to the last day of the month for any date passed in to the method

create a datetime variable set to the passed in date

Dim dtFrom As New DateTime(DateTime.Now.Year, iMonth, 1)

remove all of the days in the month except the first day and set the variable to hold that date

dtFrom = dtFrom.AddDays(-(dtFrom.Day - 1))

return the first day of the month

Return dtFrom

End Function

<summary>

Get the last day of the month for any full date

</summary>

<param name="dtDate"></param>

<returns></returns>

Private Function GetLastDayOfMonth(ByVal dtDate As DateTime) As DateTime

set return value to the last day of the month for any date passed in to the method create a datetime variable set to the passed in date

Dim dtTo As DateTime = dtDate

overshoot the date by a month

dtTo = dtTo.AddMonths(1)

remove all of the days in the next month to get bumped down to the last day of the previous month

dtTo = dtTo.AddDays(-(dtTo.Day))

return the last day of the month

Return dtTo

End Function

<summary>

Get the last day of a month expressed by it's integer value

</summary>

<param name="iMonth"></param>

<returns></returns>

Private Function GetLastDayOfMonth(ByVal iMonth As Int32) As DateTime

set return value to the last day of the month for any date passed in to the method

create a datetime variable set to the passed in date

Dim dtTo As New DateTime(DateTime.Now.Year, iMonth, 1)

overshoot the date by a month

dtTo = dtTo.AddMonths(1)

remove all of the days in the next month to get bumped down to the last day of the

previous month

dtTo = dtTo.AddDays(-(dtTo.Day))

return the last day of the month

Return dtTo

End Function

#End Region

End Class


Summary

This article was intended to demonstrate a simple approach to obtaining the first and last days of a month using a four methods each of return a DateTime value containing either the first or last day of the month. The code could be useful if one were defining something, such as SQL query terms, which required single month ranges of dates based upon user selections of single dates or months. There are of course other ways to do this but this one is pretty simple.