webdad3 webdad3 - 1 year ago 50
C# Question

ToDateTime only works when I pass in the string

When I try this:


I get the following error:

'Convert.ToDateTime(newReg.dob)' threw an exception of type

However, when I do:


It results in the following:

{3/3/2000 12:00:00 AM}

newReg.dob is a string "3/3/2000" - what is the difference? How do I get this to work?

What I'm seeing locally:

enter image description here

enter image description here

Answer Source

You better use DateTime.TryParseExact as below,

DateTime date;
if (DateTime.TryParseExact(newReg.dob.Trim(), "d/M/yyyy", CultureInfo.InvariantCulture,DateTimeStyles.None, out date))
   myPerson.personDOB =date;
   // Parse failed

By using above you can specify Culture invariant date time parse and also you can identify cases where this conversion failed, without exception.

in case of you have unwanted characters in the input string, you can use regex to get the content you want, or write simple code to filter unwanted content like below

string input ="$3/3/2000#$@#$ter ";
var outstring= new string(input.Where(c=>char.IsDigit(c)|| c=='/').ToArray()); //you get 3/3/2000 as result
// now you can pass this to above DateTime.TryParseExact method 
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download