2015-12-03 88 views
1

我在寫一個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"); 
} 
+3

http://stackoverflow.com/questions/10431835/dbnull-if-statement –

+0

http://stackoverflow.com/questions/221582/most-efficient-way-to-check-for-dbnull-然後賦值給一個變量 –

回答

1

可以使用下面的代碼檢查數據表的數據行中的空值。

if (DBNull.Value.Equals(row["Effect_Date_From"])) 
{ 
    // null 
} 
+0

謝謝你的回覆,我想知道爲什麼它說'Convert.ToDateTime(row [「Effect_Date_From」]。ToString())。ToString(「dd/MM/yyyy」 )'這一行導致異常? – RedRocket

0

您可以使用DateTime.TryParse處理無效的日期時間值,也解析日期在同一時間。

DateTime d; 
if(DateTime.TryParse(row["column"], out d)) 
{ 
//it's a valid DT 
} 
else 
{ 
//invalid 
}