February 24, 2018

ASP.NET MVC - DateTime format for each request

I was being asked this question by one of my colleague, if we can set a DateTime format at some global level so that if we need to display/process date at multiple controllers or views, we should not be worried about a specific format. I came up with this solution, I am sharing here, and welcome your suggestion or comments for any improvements or alternative solutions.

Lets say we need to display and save date in yyyy/MM/dd format. Since our server default format is set to dd/MM/yyyy, and we could not change it because some other applications might get affected, so we decided to set the required format at request level in our ASP.Net MVC application. For this we have to set the date format for current culture for each request, i.e. inside Global.asax.cs, in Application_BeginRequest() event.

Here is the real code which will set the format for current culture with the required one.

protected void Application_BeginRequest(Object sender, EventArgs e) 
{
 CultureInfo newCultureInfo = (CultureInfo)System.Threading.Thread.CurrentThread.CurrentCulture.Clone();
        newCultureInfo.DateTimeFormat.ShortDatePattern = "yyyy/MM/dd";
        //newCultureInfo.DateTimeFormat.LongDatePattern = "yyyy/MM/dd";
        //newCultureInfo.DateTimeFormat.FullDateTimePattern = "yyyy/MM/dd";
        newCultureInfo.DateTimeFormat.DateSeparator = "/";
        Thread.CurrentThread.CurrentCulture = newCultureInfo;
}

Here I am setting the DateTimeFormatInfo object's ShortDatePattern property to "yyyy/MM/dd", in CurrentCulture. Similarly you can set other required properties like LongDatePattern, FullDateTimePattern, ShortTimePattern or LongTimePattern etc. In this way you don't have to set the required date pattern in multiple places.