how do i convert data table date to a certain string format

时间:2017-08-04 12:58:05

标签: c# asp.net

string actionDate = ((DateTime) objActionDescr.GetDataTable().Rows[0]["ActionDate"]).ToString("MM");

the error comes out like i have invalid cast. Please help

1 个答案:

答案 0 :(得分:0)

首先,检查value是否为null,然后将其转换为您需要的任何格式。 像这样:

//first, check if that column contains value
if (!objActionDescr.GetDataTable().Rows[0].IsNull("ActionDate"))
{
    //if value is there, do with it what you need...

    //this will return month name, -> like August
    string actionDateMonth = (Convert.ToDateTime(objActionDescr.GetDataTable().Rows[0]["ActionDate"])).ToString("MM");
    //this will return month number -> like 08
    string actionDateMonthNumber = (Convert.ToDateTime(objActionDescr.GetDataTable().Rows[0]["ActionDate"])).ToString("mm");
    //same as above
    actionDateMonthNumber = (Convert.ToDateTime(objActionDescr.GetDataTable().Rows[0]["ActionDate"])).Month.ToString();
}