DateTime.TryParse不接受可为空的DateTime?

时间:2012-01-26 18:25:59

标签: c# datetime

所以我创建了这个可以为空的变量:

private DateTime? _startDate;

我想将一些变量解析为DateTime,然后将其分配给此变量,但VS抱怨TryParse方法有一些无效的参数。

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

我有语法错误或者我不能在这里使用可空变量吗?

4 个答案:

答案 0 :(得分:12)

正如其他人所说,他们不是兼容的类型。我建议您创建一个新方法,其中包含DateTime.TryParse返回一个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;
}

然后你可以使用:

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

(无需检查null或空字符串; TryParse无论如何都会返回false。)

答案 1 :(得分:10)

不,DateTime.TryParse()不接受DateTime?,因为DateTime?确实是Nullable<DateTime> - 不是兼容类型。

请改为尝试:

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; }

答案 2 :(得分:0)

DateTime?DateTime是与out相关的不同且不兼容的类型。所以你需要使用DateTime然后复制值,就像在Yuck的答案中一样。

答案 3 :(得分:0)

这是代码。已经处理了例外情况。

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;
        }