C# and dot net in general has a whole lot of neat built in methods to help you solve some programming tasks, some more trivial than other but most are very useful. One such task is date parsing. This is my generic date parser for c#.
I remember at varsity I had to code a toy application in c which could handle a set of dates and store them in a file a sort of log processor/analyser application, the most part of this project was just to get a nice string handling library going because 90% of what needed to be done was to parse a line of text and extract useful info like dates. The obvious problem with most of theses tasks is that one tends to “Hard Code” a parser, one unexpected line of text and the parser either breaks or produces undesirable results. To code a generic date parser in C is possible but is tiresome.
I recently was busy coding a new application, more details soon, and I needed to parse a lot of dates given in a lot of different formats, so I did some research and came up with this customizable function for converting a string into a DateTime object.
using System.Globalization;
protected DateTime StringToDateTime(string date)
{
IFormatProvider provider = CultureInfo.InvariantCulture;
DateTimeStyles style = DateTimeStyles.AllowWhiteSpaces;
//add formats here, like "dd/MM/yyyy hh:mm:ss tt" or "ddMMyyyy hh:mm"
string[] formats = new string[] { “dd/MM/yyyy”, “yyyy/MM/dd”, “MM/yyyy” };
return DateTime.ParseExact(date, formats, provider, style);
}
or alternatively to parse dates given a specific format.
using System.Globalization;
protected DateTime StringToDateTime(string date, string[] formats)
{
IFormatProvider provider = CultureInfo.InvariantCulture;
DateTimeStyles style = DateTimeStyles.AllowWhiteSpaces;
return DateTime.ParseExact(date, formats, provider, style);
}
The code uses DateTime.ParseExact to parse a string given a set of format strings.
These are only some of the common ones, well at least the ones I use most often, there are however some variations like ddd would give some thing like Mon Wed and MMM for Jan Feb, etc..
For a complete list check out:
http://msdn.microsoft.com/en-us/library/8kb3ddd4.aspx















Recent Comments