Reputation: 121
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
Upvotes: 0
Views: 239
Reputation: 532665
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);
...
}
}
Upvotes: 4