Home » Applications » VB.NET – Date in code behind

VB.NET – Date in code behind

Here is example of how we can define date in code behind:

Current month name
 
 ' - label text for current month (e.i. September) 
CMonthLbl.Text = "Current month is " & MonthName(Date.Now.Month).ToString() 
 ' - label <asp:label ID="CMonthLbl" runat="server"> 
 ' - output 
Current month is September

Other examples:

Any month name
 
 ' - your favorite month is June 
YourFavoriteMthLbl.Text = "My favorite month is " & MonthName(6).ToString() 
 ' - label 
<asp:label ID="YourFavoriteMthLbl" runat="server">
  ' - output 
My favorite month is June
First of the current month

 ' - current date 09/13/2011
 ' - 1st of the month 
FirstOfMth.Text = "From: " & DateTime.Now.Month.ToString() + "/1/" 
                   _+ DateTime.Now.Year.ToString() 
 ' - label <asp:label ID="FirstOfMth" runat="server"> 
 ' - output 
From: 09/01/2011
Month from now
 
 ' - current date 09/13/2011 
 ' - last day of the month 
MoFrmNow.Text = "End: " & DateTime.Today.AddMonth(1).AddDay(0).ToString() 
 ' - End: 09/30/2011 

Last day of the current month

 ' define var
Dim cYear, cMonth
cYear = DateTime.Now.Year 'current year needed for MoEnd range
cMonth = DateTime.Now.Month
MoEnd.Text = "End of month: " & Date.Now.Month.ToString() & "/" 
                              & DateTime.DaysInMonth(cYear, cMonth) & "/" 
                              & Date.Now.Year.ToString() & "."

End of month: 9/30/2011
Next to the current month

 ' - current date 09/13/2011 
Dim NxtMth As String NxtMth = DateTime.Now.Month + 1 
 ' - current month end or next to current month 
NextToCurMth.Text = "To: " & NxtMth.ToString() + "/1/" _ + DateTime.Now.Year.ToString() 
 ' - label <asp:label ID="NextToCurMth" runat="server"> 
 ' - output 
To: 10/01/2011
Current date in textbox
 
 ' - code behind 
Protected Sub Page_Load(sender As Object, e As System.EventArgs) Handles Me.Load 
DateTxtBx.Text = "Today is: " & _ DateTime.Now.ToShortDateString() 
DateTxtBx1.Text = "Different date format: " & _ DateTime.Now.Year.ToString() + "."  
                  _ + DateTime.Now.Month.ToString() + "." 
                  _ + DateTime.Now.Day.ToString() 
End Sub
 ' - textbox .NET control 
<asp:TextBox ID="DateTxtBx" runat="server"> 
 ' - date as 09/14/2011 <asp:TextBox ID="DateTxtBx1" runat="server"> 
 ' - date as 2011.9.14 ' - output 

Today is:

Different day format:

View related posts:
Month, day and year code behind format
VB.NET date and time format