It seems complex and doesn’t always work because it is complex. To a computer, “9/1/2017” is just a sequence of characters with no inherent meaning, in fact they are just stored as bytes. To a human it might be 9 January or 1 September; the computer does not know which interpretation is correct, so you need to tell it in some way. Also, a human reader will not even pause to recognise “9/1/2017”, “09/01/2017” and “9 January 2017” as exactly the same day in his particular culture, but purely factually they are quite different strings.
So there are more and less precise ways to do this, of which Convert.ToDateTime is the least fussy: it works on
Object variables (such DataTable cells) as well as
Strings and will not fail on variables that are null, returning
DateTime.MinValue, which is 01/01/0001 0:00.
Internally this method calls DateTime.Parse on the string representation of its input. The linked page probably has the most elaborate information on DateTime parsing. Most importantly, Parse may not recognise the format of a date unless you additionally pass it a
CultureInfo argument, e.g.
New CultureInfo("en-GB") for UK English. Note also that Parse will convert even minimal info like “9.1” and fill in the (current) year and a time of 0:00.
Perhaps the most significant other method is DateTime.ParseExact, which can take an additional string or string array containing format specifications that will be tried to parse the date string. These can look like “MM/dd/yyyy”, where MM, dd and yyyy are only three out of dozens of possibilities.
Unfortunately I cannot make this sound easy as it is not an easy topic. In short, if the dates you are handling happen to be parseable using the default culture (which is the “invariant culture”, another wonderfully confusing term), you’re in luck; if not, you will have to provide the right
CultureInfo or the right format string(s). However, please do check out the “Workflow Manager Activities” package, which has several activities pertaining to dates.