Quick fix for converting the format of the date at the application level

At times, we need to convert the format of a date for some purpose, at the application level. Read on to find out one way out

At times, we need to convert the format of a date for some purpose. 

Say, from ‘mm/dd/yy’ to ‘dd/mm/yy’.

This Code Snippet gives the easiest way to convert a date format in C#

We use the System.Globalization namespace and change the culture to 'en-GB', to do this. But that tends to cause problems to the rest of the application.

The easiest solution to this problem is to use the Overload Version provided by the ToString() method.

DateTime dtTemp = DateTime.Now;

string sTemp = dtTemp.ToString("dd/MM/yyyy");  //note that 'MM' stands for month, and 'mm' for minute.

If you want to implement this at the application level, without setting the culture to en-GB, you could put the following code in the Application_Start  Event in the Global.asax.cs file:

CultureInfo ciNewFormat = new CultureInfo(CultureInfo.CurrentCulture.ToString());

ciNewFormat .DateTimeFormat.ShortDatePattern = "dd/MM/yyyy";

System.Threading.Thread.CurrentThread.CurrentCulture = ciNewFormat ;

and after that , call the Date Variable's ToShortDateString() Method anywhere in the application like

DateTime dtTemp = DateTime.Now;

string sTemp = dtTemp.ToShortDateString();  //this would return date in ‘dd/MM/yyyy’ format

By [)ia6l0 iii   Popularity  (938 Views)