How do you centrally control the DateFormat in your ASP.NET application? So for example if you want to display the date in a dd-MM-yyyy format on each page of your application without much efforts, how would you do it?
Use the Global.asax!
The following code:
Response.Write("Today's Date Is :" + DateTime.Now.ToShortDateString());
produces the result shown below (mm/dd/yyyy):
Now to convert this dateformat ‘centrally’ to ‘dd-mm-yyyy’, follow these steps:
Create a new Global.asax file, if you do not have one in your web application. Import the following namespaces as shown here:
<%@ Import Namespace="System.Globalization" %><%@ Import Namespace="System.Threading" %>
Now in the Application_BeginRequest(), write the following code:
C#
protected void Application_BeginRequest(object sender, EventArgs e){ CultureInfo cInfo = new CultureInfo("en-IN"); cInfo.DateTimeFormat.ShortDatePattern = "dd-MM-yyyy"; cInfo.DateTimeFormat.DateSeparator = "-"; Thread.CurrentThread.CurrentCulture = cInfo; Thread.CurrentThread.CurrentUICulture = cInfo;}
VB.NET
Protected Sub Application_BeginRequest(ByVal sender As Object, _ ByVal e As EventArgs) Dim cInfo As New CultureInfo("en-IN") cInfo.DateTimeFormat.ShortDatePattern = "dd-MM-yyyy" cInfo.DateTimeFormat.DateSeparator = "-" Thread.CurrentThread.CurrentCulture = cInfo Thread.CurrentThread.CurrentUICulture = cInfoEnd Sub
Now when you run the same piece of code in any of your pages
Response.Write("Today's Date Is :" + DateTime.Now.ToShortDateString());
you get the following output:
LATEST NEWS
