c#创建没有时间的datetime对象

时间:2017-01-05 20:38:51

标签: c# datetime

我正在尝试从数据库加载一些日期,但我不想用时间创建日期时间对象,我只想要日期。我试过了 var date = value.Date;它没有用。我已经看到很多方法基本上格式化日期以将其显示为字符串,我不想这样做,因为我必须手动将所有数据加载到网格中。我希望有一个人可以帮助我。这是代码

next

2 个答案:

答案 0 :(得分:3)

您是否需要使用DateTime的任何功能,例如比较日期或添加/减去日期中的天数?如果没有,您可以只使用变量字符串而不是DateTimes:

string startDate = ((DateTime)row["Course_StartDate"]).ToShortDateString();
string endDate = ((DateTime)row["Course_EndDate"]).ToShortDateString();

编辑:由于您确实需要比较时间,因此可以使用第二个属性,根据需要返回等效值:

DateTime startDate = new DateTime();
DateTime endDate = new DateTime();
string startDateString
{
    get
    {
        return startDate.ToShortDateString();
    }
}
string endDateString
{
    get
    {
        return endDate.ToShortDateString();
    }
}

private void LoadMethod()
{
    startDate = (DateTime)row["Course_StartDate"];
    endDate = (DateTime)row["Course_EndDate"];
}

然后,您可以使用DateTime对象进行数学运算,并使用表格中的字符串对象。

答案 1 :(得分:1)

如果您正在谈论DataGridView,请将列格式(DefaultCellStyle>格式)更改为 MM / dd / yyyy