webdad3 webdad3 - 16 days ago 6
C# Question

ToDateTime only works when I pass in the string

When I try this:

Convert.ToDateTime(newReg.dob)


I get the following error:


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


However, when I do:

Convert.ToDateTime("3/3/2000")


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

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;
}
else
{
   // 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