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

image

Share:
  • Print
  • Digg
  • Sphinn
  • del.icio.us
  • Facebook
  • Mixx
  • Google Bookmarks
  • DZone
  • LinkedIn
  • Reddit
  • StumbleUpon
  • Twitthis
This entry was posted in ASP.Net, Syndicated. Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Spam Protection by WP-SpamFree