Find the First and Last Days of the Month with C#


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 date's month and year along with manually setting the new date's day to "1" as shown below.

DateTime dt = 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.

FirstAndLastDay1.gif

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

Getting Started

The solution contains a single Windows Forms project called "FirstLastDay" which was written in C#; the application contains a single Windows form (Form1.cs); 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.

FirstAndLastDay2.gif

Figure 2:  Solution Explorer with the Project Visible

Code:  Main Form (Form1.cs)

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's methods, and to display the results to the user.

The class begins with the standard imports; nothing has been added here.

using System;

using System.Collections;

using System.ComponentModel;

using System.Data;

using System.Drawing;

using System.Text;

using System.Windows.Forms;

 

namespace FirstLastDay

{

 

    /// <summary>

    /// Example of one approach to obtaining the

    /// first and last days of any given month

    /// </summary>

    public partial class frmFirstAndLast : Form

    { 

 

The constructor is shown following the namespace and class declarations; 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>

        public frmFirstAndLast()

        {

            InitializeComponent();

 

            // creat an array of all of the months

            string[] months = {"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;

        }

 

#endregion

 

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>

        private void btnFind_Click(object sender, EventArgs e)

        {

            // 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

            string[] dateParts = txtFirstDay.Text.Split('/');

            DateTime dtFirstTemp = 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

            string[] dateParts2 = txtLastDay.Text.Split('/');

            DateTime dtLastTemp = 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();

        } 

 

        /// <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>

        private void btnFind2_Click(object sender, EventArgs e)

        {

            // 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

            string[] dateParts = txtFirstDay2.Text.Split('/');

            DateTime dtFirstTemp = 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

            string[] dateParts2 = txtLastDay2.Text.Split('/');

            DateTime dtLastTemp = 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();

 

            DateTime dt = new DateTime(dtpDate.Value.Year,

                dtpDate.Value.Month, 1);

        }

  

        /// <summary>

        /// Exit the Application

        /// </summary>

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

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

        private void btnExit_Click(object sender, EventArgs e)

        {

            this.Dispose();

        }

 

#endregion

 

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 DateTime GetFirstDayOfMonth(DateTime dtDate)

        {

            // 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

            DateTime dtFrom = 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;

        }

        

        /// <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 DateTime GetFirstDayOfMonth(int iMonth)

        {

            // 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

            DateTime dtFrom = 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;

        }

  

        /// <summary>

        /// Get the last day of the month for any

        /// full date

        /// </summary>

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

        /// <returns></returns>

        private DateTime GetLastDayOfMonth(DateTime dtDate)

        {

            // 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

            DateTime dtTo = 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;

        }

  

        /// <summary>

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

        /// integer value

        /// </summary>

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

        /// <returns></returns>

        private DateTime GetLastDayOfMonth(int iMonth)

        {

 

            // 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

            DateTime dtTo = 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;

 

        }

 

#endregion

   }

}

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.

Up Next
    Ebook Download
    View all
    Learn
    View all