I have a problem.
This is not working
> var from = ""; > StartDTime = Convert.ToDateTime(from);
This is working
> var from = "2021-10-05"; > StartDTime = Convert.ToDateTime(from);
Some time I’m sending Date Value, but sometime in not sending Date Value.in that time from
variable pass as a empty string. I want to set if from variable is = "" then need to set default Date Value.so how can I resolve this?. Please help me guys. Thank you
5
Answers
DateTime.TryParse will do the job for you:
for example:
One-liner, with only the validation you specify:
Convert
methods either successfully convert the string passed to it, or throws an error, that’s the way it’s supposed to work. For most data types there are alsoTryParse
methods that return true/false based on if it converted successfully and have an output variable which will beDateTime.MinValue
if it failed. This is how I would handle your situation:This will set the startTime to the date passed in from, but if no date was passed it sets it to the current date and time – if you want a different default value, that replaces
new DateTime()
and if your default should be January 1, 0001, then you can just use the TryParse part directly, since that’s the automatic default for a failed TryParse.A safe way of doing that would be:
But if you have control over the code passing the "from" variable, you can declare it as nullable DateTime, then your code would look like this:
Which for short would be:
It’s not ellegant, but works.
But i think that a nullable DateTime would be more elegant, like this:
Or you can set a default date, like this: