How can I get DateTime
value in C# from row, the current code is giving me error
any help is appreciated, the data is coming in from progress database:
DateTime.Parse(r["FISS"].ToString()) is the way to go, but it throws a "String was not recognized as a valid DateTime" error. Could you show the actual string in the r["FISS"] column, it might be a internationalisation problem....
If you want to use a default value (such as DateTime.MinValue), rather than null (DateTime?) or DBNull, you could do this:
var firstIssueDate = r["FISS"] as DateTime? ?? DateTime.MinValue;
var endIssueDate = r["EISS"] as DateTime? ?? DateTime.MinValue;
If you have a DateTime string with a special format (not any standard .NET DateTime format) that needs to be converted to .NET DateTime type, you can use DateTime.ParseExact()
method.
Please see the MSDN document for more details including examples.
If you have multiple formats to parse, try DateTime.ParseExact Method (String, String[], IFormatProvider, DateTimeStyles)
First of all, do r["FISS"].GetType() and print it to console (or pause and look at it in the debugger). If it says it's a String, then most of the above advices will help. If it says something else, please come back and update your question.
As a side answer, you could use also the static function Convert.ToDateTime
foreach (DataRow r in ds.Tables[0].Rows)
{
string prodCode = r["PRD-CDE"].ToString();
string statCode = r["STAT"].ToString();
DateTime firstIssueDate = DateTime.Parse((r["FISS"]).ToString());
DateTime endIssueDate = DateTime.Parse((r["EISS"]).ToString());
if(endIssueDate > DateTime.Now)
{ /*do some thing...*/}
else {/*user invalid...*/}
}
This should compile and may work for you. Though it is certainly not performing any error checking that you should do for production code. Also look into DateTime.TryParse and you may to look into adding a IFormatProvider to ensure the format is parsed as expected.