How to convert to DateTime but have default value if input is blank?

CJ7 picture CJ7 · Feb 12, 2013 · Viewed 15.7k times · Source

What .NET function will convert to a DateTime but have a default value if input is blank?

eg.

DateTime dtTest = Convert.ToDateTime(getDateString());

If getDateString() returns an empty string Convert.ToDateTime throws an exception.

How can I instead have a default value of "9:00AM" used instead of the empty string? Is this something where TryParse could be used?

Answer

Habib picture Habib · Feb 12, 2013

Use DateTime.TryParse and if the parsing fails you can assign DateTime.MinValue.AddHours(9) to get (9:00AM) time with Minimum Date.

string str = "";
DateTime temp;
DateTime dt = DateTime.TryParse(str, out temp) ? temp : DateTime.MinValue.AddHours(9);

For the above code your dt object will hold {01/01/0001 9:00:00 AM}