In this article I will explain with an example, how to display Date in
yy/M/d format in
ASP.Net with C# and VB.Net.
HTML Markup
The
HTML Markup consists of:
Label – For displaying formatted Date in yy/M/d format.
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
Date (yy/M/d): <asp:Label ID="lblFormattedDate" runat="server" />
</form>
</body>
</html>
Namespaces
You will need to import the following namespace.
C#
using System.Globalization;
VB.Net
Imports System.Globalization
Displaying Date in yy/M/d format in ASP.Net
Inside the Page_Load event handler, the Current DateTime is set into the DateTime object and then it is formatted to the desired (yy/M/d) date with the help of ToString method.
Note: Here
ToString is passed with the desired Date Format and the Culture. Below are the details: -
yy – Year in 2 characters i.e. 85
M - Month in 1 character for single digit i.e. 2
d – Day in 1 character for single digit i.e. 5
C#
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
//Get the Current Date and Time.
DateTime today = DateTime.Now;
//Format the DateTime in yy/M/d.
lblFormattedDate.Text = today.ToString("yy/M/d", CultureInfo.InvariantCulture);
}
}
VB.Net
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
If Not Me.IsPostBack Then
'Get the Current Date and Time.
Dim today As DateTime = DateTime.Now
'Format the DateTime in yy/M/d.
lblFormattedDate.Text = today.ToString("yy/M/d", CultureInfo.InvariantCulture)
End If
End Sub
Screenshot
Month and Day with 2 characters
Month and Day with 1 character
Demo
Downloads