简体   繁体   中英

DateTime.TryParse doesn't accept nullable DateTime?

so I have this nullable variable I created:

private DateTime? _startDate;

I wanted to parse some variable to DateTime and then assign it to this variable, but the VS complains that the TryParse method has some invalid arguments.

if (string.IsNullOrEmpty(Request.Form["StartDate"]) == false)
        {
            DateTime.TryParse(Request.Form["StartDate"], out _startDate);
        }
        else
        { _startDate = null; }

Is there a syntax error I have or I can't use nullable variables in here?

As others have said, they're not compatible types. I would suggest you create a new method which wraps DateTime.TryParse and returns a Nullable<DateTime> :

// Add appropriate overloads to match TryParse and TryParseExact
public static DateTime? TryParseNullableDateTime(string text)
{
    DateTime value;
    return DateTime.TryParse(text, out value) ? value : (DateTime?) null;
}

Then you can just use:

_startDate = Helpers.TryParseNullableDateTime(Request.Form["StartDate"]);

(No need to check for null or empty string; TryParse will just return false in that case anyway.)

No, DateTime.TryParse() doesn't accept DateTime? because DateTime? is really Nullable<DateTime> - not a compatible type.

Try this instead:

if (string.IsNullOrEmpty(Request.Form["StartDate"]) == false)
    {
        var dtValue = new DateTime();
        if (DateTime.TryParse(Request.Form["StartDate"], out dtValue)) {
            _startDate = dtValue;
        }
        else {
            _startDate = null;
        }
    }
    else
    { _startDate = null; }

DateTime? and DateTime are different and non-compatible types in relation to out . So you need to use DateTime and then copy value as in Yuck's answer.

Here's the code. Exception is been handled.

if (string.IsNullOrEmpty(Request.Form["StartDate"]) == false)
        {
            DateTime strtDate;
            try
              {
                strtDate = Convert.ToDateTime(Request.Form["StartDate"]);
                _startDate = strtDate;
              }
            catch(Exception)
              {
               _startDate = null;
              }
         }
        else
        { 
       _startDate = null;
        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM