我在寫一個web應用程序。我想檢查dateFrom是否爲null或者如果dateTo爲null。如果dateFrom爲null,則輸出dateTo,如果dateTo爲null,則輸出dateFrom。如果兩者都存在,則打印出陣列,如12/3/2015 - 12/3/2015
。我有大部分的代碼工作,但我不知道如何處理空日期。它不斷給我這個例外如何檢查dataRow中的dateTime是否爲空?
字符串未被識別爲有效的DateTime
這裏是我的代碼
public DataSet SearchTimingReq()
{
DateTime effectDateFrom, effectDateTo;
DataSet ds = someDataSet();
if (ds != null && ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
{
foreach (DataRow row in ds.Tables[0].Rows)
{
if (Convert.ToDateTime(row["Effect_Date_To"].ToString()).ToString("dd/MM/yyyy") == DateTime.MinValue.ToString())
{
row["Effective_Period"] = effectDateFrom.ToString("dd/MM/yyyy");
}
if (Convert.ToDateTime(row["Effect_Date_From"].ToString()).ToString("dd/MM/yyyy") == DateTime.MinValue.ToString())
{
row["Effective_Period"] = effectDateTo.ToString("dd/MM/yyyy");
}
if (effectDateTo != DateTime.MinValue && effectDateFrom == DateTime.MinValue)
{
row["Effective_Period"] = Convert.ToDateTime(row["Effect_Date_From"].ToString()).ToString("dd/MM/yyyy") + " - " + Convert.ToDateTime(row["Effect_Date_To"].ToString()).ToString("dd/MM/yyyy");
}
}
}
}
更新代碼
if (!DBNull.Value.Equals(row["Effect_Date_From"]))
{
row["Effective_Period"] = Convert.ToDateTime(row["Effect_Date_To"].ToString()).ToString("dd/MM/yyyy");
}
if (!DBNull.Value.Equals(row["Effect_Date_To"]))
{
row["Effective_Period"] = Convert.ToDateTime(row["Effect_Date_From"]).ToString("dd/MM/yyyy");
}
if (DBNull.Value.Equals(row["Effect_Date_To"]) && DBNull.Value.Equals(row["Effect_Date_From"]))
{
row["Effective_Period"] = Convert.ToDateTime(row["Effect_Date_From"].ToString()).ToString("dd/MM/yyyy") + " - " + Convert.ToDateTime(row["Effect_Date_To"].ToString()).ToString("dd/MM/yyyy");
}
http://stackoverflow.com/questions/10431835/dbnull-if-statement –
http://stackoverflow.com/questions/221582/most-efficient-way-to-check-for-dbnull-然後賦值給一個變量 –