In my database I have a field date of type varchar where the date is stored in the following format yyyyMMddhhmm, with no spaces or other characters separating them.
Now I need to compare this date with a C# DateTime, therefore I need to convert the string into DateTime. The most logical way that I can think of is to extract from the variable date the sub-string related to year, month and day and create a new DateTime object:
var year = Convert.ToInt32(date.Substring(0, 4));
var month = Convert.ToInt32(date.Substring(4, 2));
var day = Convert.ToInt32(date.Substring(6, 2));
DateTime dateToCompare = new DateTime(year, month, day);
Is there any available C# method that allows me to perform this conversion without writing all this code?
Absolutely – use
DateTime.ParseExact:Note the
HHfor 24-hour instead ofhhfor 12-hour format.Alternatively, you could use
DateTime.TryParseExact, which returns a true/false value to indicate whether or not the parsing was successful. If you’re fully expecting all the data to be valid, and it’s reasonable for an exception to be thrown otherwise, thenDateTime.ParseExactis fine.As a very different alternative, you could use Noda Time:
Or for the “just throw an exception” behaviour, just use
parseResult.Valueunconditionally.EDIT: As an aside, is there any reason why you’re storing dates in a varchar column? Can you fix your schema instead?