DateTime get beginning of month
The following asp.net c# example code demonstrate us how can we get the first day of a month from a given
DateTime object programmatically at run time in an asp.net application. By default, .net framework's DateTime Class
has no method or property to get first day of a month. So we need to follow some techniques to get it.
First, we store the specified date to a DateTime variable. Next, we initialize a new DateTime object from the given DateTime object's Year part, Month part and First day such as 2014/12/1 (DateTime.Year/DateTime.Month/1). We only take the year and month part from the given DateTime object and create a new date from it where day number is 1. Finally, we get the first day of month/beginning of a month from a specified date.
First, we store the specified date to a DateTime variable. Next, we initialize a new DateTime object from the given DateTime object's Year part, Month part and First day such as 2014/12/1 (DateTime.Year/DateTime.Month/1). We only take the year and month part from the given DateTime object and create a new date from it where day number is 1. Finally, we get the first day of month/beginning of a month from a specified date.
datetime-beginning-of-month.aspx
<%@ Page Language="C#" AutoEventWireup="true"%>
<!DOCTYPE html>
<script runat="server">
protected void Button1_Click(object sender, System.EventArgs e)
{
//initialize a datetime variable with today
DateTime today = DateTime.Today;
//create a datetime object with first day of current month
DateTime firstDayOfMonth = new DateTime(today.Year,today.Month,1);
Label1.Text = "Today : " + today.ToLongDateString();
Label1.Text += "<br />first day of month : ";
Label1.Text += firstDayOfMonth.ToLongDateString();
}
</script>
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title>c# example - datetime beginning of month</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<h2 style="color:MidnightBlue; font-style:italic;">
c# example - datetime beginning of month
</h2>
<hr width="550" align="left" color="Gainsboro" />
<asp:Label
ID="Label1"
runat="server"
Font-Size="Large"
Font-Names="Comic Sans MS"
>
</asp:Label>
<br /><br />
<asp:Button
ID="Button1"
runat="server"
Text="get first day of month"
OnClick="Button1_Click"
Height="40"
Font-Bold="true"
/>
</div>
</form>
</body>
</html>

- How to get days between two DateTimes
- How to subtract two DateTimes
- How to get the number of days in a given month
- How to create a TimeSpan
- How to check if a DateTime is later than another date
- How to get the last day of month using a given date
- How to get the month name from month number
- How to get the first day of week
- How to get the integer value of day of week
- How to get two DateTime objects difference in milliseconds