Retrieving a DateTime value from a DataRow (C#)

后端 未结 8 1283
别跟我提以往
别跟我提以往 2020-12-09 04:06

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:

相关标签:
8条回答
  • 2020-12-09 04:12

    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....

    0 讨论(0)
  • 2020-12-09 04:16

    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;
    
    0 讨论(0)
  • 2020-12-09 04:21

    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)

    0 讨论(0)
  • 2020-12-09 04:22

    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.

    0 讨论(0)
  • 2020-12-09 04:23

    As a side answer, you could use also the static function Convert.ToDateTime

    0 讨论(0)
  • 2020-12-09 04:24
    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.

    0 讨论(0)
提交回复
热议问题