可以为null的dateTime而不丢失方法

时间:2014-11-03 09:51:01

标签: c# datetime nullable

我已经制作了一个将datetime对象转换为仅限日期格式的方法。为了访问它,我必须将my参数的值赋给将在数据表中的值。因此,显而易见的方法是在DateTime对象之后添加?以使其可为空,但是这会删除它的方法(或者至少是我需要使用的方法),这使得我的方法毫无价值。

string dateWithOutTime(DateTime? datetime)
{
    string reply = datetime.Date.ToString();
    return reply;
}

用法:

string str = dateWithOutTime(*DataSet*.*DataTable[n]*.Rows[n][n] as DateTime?);

有没有办法在不添加任何额外对象的情况下完成此操作?

注意:星号(*)表示变量类型/对象

2 个答案:

答案 0 :(得分:2)

DateTime?DateTime的方法不同,它们的类型不同。您必须使用DateTime? Value属性检索实际日期时间值:

string dateWithOutTime(DateTime? datetime)
{
    if(datetime.HasValue)
        return datetime.Value.Date.ToString();
    else
        return //...

}

阅读Nullable<T> here的文档。

答案 1 :(得分:1)

除非我误解了你的问题,否则我说你需要检查一下你的DateTime?参数为null或不为空。如果是,则返回一个空字符串(或者您想要显示缺少日期的字符串)。如果不是,您可以使用Value属性:

string dateWithOutTime(DateTime? datetime)
{
    return datetime.HasValue ? datetime.Value.Date.ToString() : String.Empty;
}

更新

如果您只想要字符串中的日期部分,并且希望它对文化敏感,则可以使用ToShortDateString()代替ToString()。你甚至可以省略Date财产:

string dateWithOutTime(DateTime? datetime)
{
    return datetime.HasValue
        ? datetime.Value.ToShortDateString()
        : String.Empty;
}
相关问题