0

I need some guidance for parsing dates. My database table contains values ID (int) and date (datetime: yyyy-mm-dd HH:mm:ss.fff format) and status example

1000 & 2014-02-18 20:32:20.657 & 1
2000 & 2014-02-18 20:32:20.658 & 1
3000 & NULL                    & -1

I have a C# program that looks at this table for status=1 and date not null and want to insert ID and Date in the same format in a text file. The text file should have

1000    2014-02-18 20:32:20.657
2000    2014-02-18 20:32:20.658

Here's the code.

using (SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["SQLConnectionString"].ConnectionString))
{
    connection.Open();
    SqlCommand cmdSel = new SqlCommand(sqlSelNew, connection);
    SqlDataReader reader1 = cmdSel.ExecuteReader();
    while (reader1.Read())
    {
      DataSet ds = GetData(sqlSelNew);
      CultureInfo _provider = CultureInfo.InvariantCulture;
       ID = Convert.ToInt32(reader1["ID"].ToString());
       string dtformat = @"yyyy/MM/dd HH:mm:ss.fff";
       var d = DateTime.ParseExact(dateresized,dtformat , _provider);
       using (StreamWriter sw = new StreamWriter(txtfilepath, true))
        {
            sw.BaseStream.Seek(0, SeekOrigin.End);
            sw.WriteLine(ID + "   " + d);
            sw.Flush();
            sw.Close();
        }

I get "String was not recognized as a valid DateTime." error. How can I handle this? Thanks Rashmi

1 Answer 1

4

First, you shouldn't have to parse the date. You should simply be able to use reader.GetDateTime() to read that column and assign it. Second, why are you both filling up a DataSet and using a SqlDataReader to get the values directly? I'd expect one or the other but not both. Third, you ought to be wrapping your reader in a using statement as it implements IDisposable.

using (var reader1 = cmdSel.ExecuteReader())
{
    while (reader1.Read())
    {
       var id = reader1.GetInt32(0);
       var date = reader1.GetDateTime(1);

       ...
    }
}
Sign up to request clarification or add additional context in comments.

2 Comments

I made the changes above. txt file has date in different format i.e. 1000 2/18/2014 9:04:06 PM instead of 2014-02-11 21:04:06.770
@Rashmi - you need to use a format on the data output, not in parsing the input, to specify what you want, e.g., sw.WriteLine("{0} {1:yyyy/MM/dd HH:mm:ss.fff}", id, date);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.