Pages

Tuesday 21 January 2014

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

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

No comments:

Post a Comment