tags:

views:

4724

answers:

3

I am trying to convert all DateTime values in a DataTable to strings. Here is the method I use:

private static void ConvertDateTimesToStrings(DataTable dataTable)
{
    if (dataTable == null)
    {
        return;
    }

    for (int rowIndex = 0; rowIndex < dataTable.Rows.Count; rowIndex++ )
    {
        for (int i = 0; i < dataTable.Columns.Count; i++)
        {
            DateTime dateTime;
            try
            {
                dateTime = (DateTime)dataTable.Rows[rowIndex][i];
            }
            catch (InvalidCastException)
            {
                continue;
            }
            dataTable.Rows[rowIndex][i] = dateTime.ToString("dd.MM.yyyy hh:mm:ss");
        }
    }
}

After this line works:

dataTable.Rows[rowIndex][i] = dateTime.ToString("dd.MM.yyyy hh:mm:ss");

I check the value of dataTable.Rows[rowIndex][i] and see it is still a DateTime, not a string. Why does this happen and how can I solve this?

Edit: I am trying to do this because I am fighting an api and unfortunately I do not have the choice of which component to use.

+10  A: 

This simply won't work, because you haven't changed the underlaying data type.

You have a DataTable, with a column which has data type DateTime.

You can assign a String to it, but it will convert back to DateTime.

Why do you want to change it to a formatted string? Can't you format only when you need to display it, and handle as a DateTime until you have to display it?

Update: it is also better if you check the column's type before you try to convert, it can be much faster:

if (dataTable.Columns[0].DataType == typeof(DateTime))
{
}
Biri
+3  A: 

It may have determined that the column data type is date time and is reboxing the values to datetime when you save the value back in there.

Try this... Create a new column on the datatable as a TypeOf(String), and save the string value into that column. When all the values have been copied, drop the date time column.

StingyJack
I solved it using your solution and Biri's information. Thank you both.
Serhat Özgel
A: 

It won't work beacuse the DataType of the column is still DateTime and it'll convert the string back to datetime. I'd suggest to format the date to string when generating your API message. If you still need to generate a string column for datetime values

foreach (DataColumn column in dataTable.Columns) {
  if (column.DataType == typeof(DateTime)) {
    dataTable.Columns.Add(column.ColumnName + "_string", typeof(string));
  }
}

foreach (DataRow row in dataTable.Rows) {
   foreach (DataColumn column in dataTable.Columns) {
     if (column.DataType == typeof(DateTime)) {
       row[column.ColumnName + "_string"] = row[column.ColumnName].ToString("dd.MM.yyyy hh:mm:ss");
     }
   }
}

Then you can remove all DateTime columns or use a dataTable.Select() to get only the columns you need. PS: I didn't test the code, it's up to you.

Eduardo Campañó