How to use datetime function on null value string without throwing any exception

时间:2017-06-19 13:59:45

标签: c# datetime

I have been using C# for trying to parse a string into datetime format. It works as long as the string is not null but fails when its null. I used datetime.parse but it failed:

Datetime.parse:

 Datetime ContactDate =   DateTime.Parse((GetContactDateForClient(1)?.DisplayText))  -- (note: getcontactdateforclient.displaytext is one of my method which gets back date in string format)

Whenever my method gets back date as non null the above works great but if its null then my above line of code fails. I tried datetime.tryparse but it shows me error during compilation ("Cannot convert System.Datetime ? to System.Datetime")
Datetime.TryParse:

        DateTime value;
        Datetime ContactDate = DateTime.TryParse((GetContactDateForClient(1)?.DisplayText), out value)  ? value: (DateTime?) null;

Is it possible to assign 'ContactDate' value as null if the string is null and if not null then get the value as it comes back(GetContactDateForClient(1)?.DisplayText). Any pointer much appreciated.

3 个答案:

答案 0 :(得分:2)

You need to declare a nullable datetime

try this

Datetime? ContactDate = DateTime.TryParse((GetContactDateForClient(1)?.DisplayText), out value)  ? value: (DateTime?) null;

答案 1 :(得分:1)

Is it possible to assign 'ContactDate' value as null

Sure, just make it a nullable type:

Datetime? ContactDate = DateTime.TryParse(...

That's what the original error was telling you:

"Cannot convert System.Datetime? to System.Datetime"

You were trying to assign a DateTime? (nullable DateTime) to a DateTime. They're different types. Just use the same consistent type.

答案 2 :(得分:1)

You can try:

Datetime ContactDate =   DateTime.Parse((GetContactDateForClient(1)?.DisplayText ?? "your default value"))