Thursday, March 8, 2012

Dealing with DateTime in C#

Recently I come across very ugly error which makes my application crashed. Actually it was problem converting DateTime for specific format. You should make your DateTime conversion independent of client computer’s culture setting.  This thought in mind I am going to present this post.

1.       Convert String  to DateTime

Let’s take an example:

Suppose you have
 String strDate = "10/23/2011"; 

Which is in MM/dd/yyyy format and you want to convert it in DateTime variable then you should write like
 DateTime dt = Convert.ToDateTime(strDate,System.Globalization.CultureInfo.InvariantCulture); 

You could write above code if you are sure that the format is in MM/dd/yyyy. If the format is in say dd/MM/yyyy then DatTime.ParseExact is the perfect option for you.

Code above can be rewritten as
 DateTime dt = DateTime.ParseExact(strDate, "dd/MM/yyyy", System.Globalization.CultureInfo.InvariantCulture); 
In all above code lines I have mentioned System.Globalization.CultureInfo.InvariantCulture parameter, which will make date format, culture independent.

2.       Convert Datetime to Specific Format

Let’s say you have
 DateTime dt = DateTime.Now; 
and you want to convert it in different format. 

Example : Format : dd-mmm-yyyy
 String s = dt.ToString("dd/MMM/yyyy"); 

But this will be overridden by current culture.

So you should do something like this
String s = dt.ToString("dd/MMM/yyyy", System.Globalization.CultureInfo.InvariantCulture); 

In short, CultureInfo parameter plays an important role.

No comments: