In this article I will explain with an example, how to find first and last day of month in ASP.Net using C# and VB.Net.
HTML Markup
The HTML Markup consists of following controls:
Button – For finding first day and last of the month hence two Buttons are used.
The Buttons have been assigned with an OnClick event handler.
The Buttons have been also assigned with the CommandName property set to First and Last for respective Buttons.
Label – For displaying found date.
<table>
<tr>
<td>
<asp:Button runat="server" Text="Month First Day" OnClick="OnMonthFirstLastDay" CommandName="First"/></td>
<td>
<asp:Label ID="lblFirstDay" runat="server" /></td>
</tr>
<tr>
<td>
<asp:Button runat="server" Text="Month Last Day" OnClick="OnMonthFirstLastDay" CommandName="Last" /></td>
<td>
<asp:Label ID="lblLastDay" runat="server" /></td>
</tr>
</table>
Finding first and last day of month using C# and VB.Net
When Submit Button is clicked, an object of DateTime is created and the date is passed as parameter.
Finding First date
Then, another object of DateTime is created where the Year and Month of the specified date set earlier is passed as parameter with date 1.
Finding Last date
Another DateTime object is created and the AddMonths method is called with parameter 1 using DateTime object created for finding first day of month and AddMinutes is also called with -1 as parameter.
Finally, a check is performed for CommandName value and based on the triggered Button the Label is set with date.
C#
protected void OnMonthFirstLastDay(object sender, EventArgs e)
{
DateTime date_time = new DateTime(2025, 1, 18);
// Calculate first day of month.
DateTime firstDayOfMonth = new DateTime(date_time.Year, date_time.Month, 1);
// Calculate last day of month.
DateTime lastDayOfMonth = firstDayOfMonth.AddMonths(1).AddMinutes(-1);
if ((sender as Button).CommandName.ToUpper() == "FIRST")
{
this.lblFirstDay.Text = firstDayOfMonth.ToString("dd dddd");
}
if ((sender as Button).CommandName.ToUpper() == "LAST")
{
this.lblLastDay.Text = lastDayOfMonth.ToString("dd dddd");
}
}
VB.Net
Protected Sub OnMonthFirstLastDay(sender As Object, e As EventArgs)
Dim date_time As DateTime = New DateTime(2025, 1, 18)
' Calculate first day of month.
Dim firstDayOfMonth As DateTime = New DateTime(date_time.Year, date_time.Month, 1)
' Calculate last day of month.
Dim lastDayOfMonth As DateTime = firstDayOfMonth.AddMonths(1).AddMinutes(-1)
If (TryCast(sender, Button)).CommandName.ToUpper() = "FIRST" Then
Me.lblFirstDay.Text = firstDayOfMonth.ToString("dd dddd")
End If
If (TryCast(sender, Button)).CommandName.ToUpper() = "LAST" Then
Me.lblLastDay.Text = lastDayOfMonth.ToString("dd dddd")
End If
End Sub
Screenshot
Demo
Downloads