I am writing an web application. I want to check if the dateFrom is null or if dateTo is null. If dateFrom is null, print out dateTo, if dateTo is null, then print out dateFrom. If both of then exist, then print out the formation such as 12/3/2015 - 12/3/2015
. I have most of the code working, but I cannot figureout how to handle the null date. It keep giving me this exception
String was not recognized as a valid DateTime
Here is my code
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");
}
}
}
}
Updated code
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");
}