TheChief TheChief - 1 month ago 15
C# Question

C# formatting sql table date column output when writing to text file

My issue is I am trying to generate text files to email through my program. The program searches the sql table for date firstname lastname and some other columns and of course its writing the date and time into the file. I only want to write the date instead of the date and time into the text files.

Logic being used:
1. query data from sql
2. insert data into dataset
3. create datatable from dataset
4. write datatable to txt file

This is how it's being written into the text file

1/20/2014 12:00:00 AM | 76770 | 1/1/1900 12:00:00 AM | 0.0000 |

1/28/2014 12:00:00 AM | 74000 | 1/1/1900 12:00:00 AM | 0.0000 |

1/20/2014 12:00:00 AM | 76770 | 2/19/2014 1:02:47 PM | 28.5600 |

1/28/2014 12:00:00 AM | 74000 | 2/24/2014 11:50:32 AM | 7.0000 |

using this code:

public void writeData(StreamWriter sw, DataTable data)
{
int i;
sw.Write(Environment.NewLine);
foreach (DataRow row in data.Rows)
{
object[] array = row.ItemArray;
for (i = 0; i < array.Length - 1; i++)
{
sw.Write(array[i] + "\t | ");
}
sw.WriteLine(array[i]);
}
sw.Write(Environment.NewLine + "*****END OF DATA****" + Environment.NewLine + "Retrieved: " + DateTime.Now.ToString());
dataGridView1.DataSource = finalTable;
}


I want it to look like this in the txt file
1/20/2014 | 76770 | 1/1/1900 | 0.0000 |

1/28/2014 | 74000 | 1/1/1900 | 0.0000 |

1/20/2014 | 76770 | 2/19/2014 | 28.5600 |

1/28/2014 | 74000 | 2/24/2014 | 7.0000 |

is there a way to shorten the dates like that?

Answer

You could try this - I've also added an additional case to format any decimal values to currency format.

foreach (DataRow row in data.Rows)
{
    for (i = 0; i < row.ItemArray.Length; i++)
    {
        if ( row.Table.Columns[i].DataType == typeof(System.DateTime))
            sw.Write( ((DateTime)(row.ItemArray[i])).ToString("dd/MM/yyyy") + "\t | ");
        else if ( row.Table.Columns[i].DataType == typeof(System.Decimal))
            sw.Write( ((decimal)(row.ItemArray[i])).ToString("C") + "\t | ");
        else
            sw.Write(row.ItemArray[i] + "\t | ");
    }
    sw.WriteLine();
}
Comments