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?
Try setting the value of the date to 0000-00-00, this usually works (never tried it in this scenario but everywhere else it always worked for me).
DateTime itself is a value type. It cannot be null.
ToString() − One more way to get the date from DateTime is using ToString() extension method. The advantage of using ToString() extension method is that we can specify the format of the date that we want to fetch. DateTime. Date − will also remove the time from the DateTime and provides us the Date only.
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}
I have used something called a ternary statement. You can view an example here: MSDN
string myDate = getDateString();
DateTime dtTest = Convert.ToDateTime(String.IsNullOrEmpty(myDate) ? "my default value" : myDate);
The ternary statement is below:
String.IsNullOrEmpty(myDate) ? "my default value" : myDate
And it can be read as follows:
If the string is null or empty, then use "my default value", otherwise use myDate.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With