October 7, 2009

Set the DateFormat in Global.asax




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):

image

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 = cInfo
End 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:

image



'Like' us on our FaceBook page if you find this blog useful. Thanks!


Did you like this post?
kick it on DotNetKicks.com Save on Delicious
subscribe via rss subscribe via e-mail
print this post follow me on twitter


About The Author

Suprotim Agarwal, ASP.NET Architecture MVP works as an Architect Consultant and provides consultancy on how to design and develop Web applications.

Suprotim is also the founder and primary contributor to DevCurry, DotNetCurry and SQLServerCurry. He has also written an EBook 51 Recipes using jQuery with ASP.NET Controls.

Follow him on twitter @suprotimagarwal

comments

0 Responses to "Set the DateFormat in Global.asax"
 

Copyright © 2009-2012 All Rights Reserved for DevCurry.com by Suprotim Agarwal | Terms and Conditions