neo
neo

Reputation: 457

Changing Date Column data format for a Data Column in data table

How to change Date Column data format for a Data Column in data table through program. How to achieve this seeking help. I am exporting datatable to CSV. In csv my Date format should be of "yyyy/MM/dd hh:mm".

Upvotes: 0

Views: 1563

Answers (1)

Tim Schmelter
Tim Schmelter

Reputation: 460370

If you want to create a CSV file from a DataTable and apply a specific format to a date-column you can use DateTime.ToString with a custom format string.

In your case you want. yyyy/MM/dd hh:mm. But since / will be replaced by your current date separator you either have to escape it(yyyy'/'MM'/'dd hh:mm) or use CultureInfo.InvariantCulture.

StringBuilder sb = new StringBuilder(); 

IEnumerable<string> columnNames = dt.Columns.Cast<DataColumn>().
                                  Select(column => column.ColumnName);
sb.AppendLine(string.Join(",", columnNames));

var inv = CultureInfo.InvariantCulture;
foreach (DataRow row in dt.Rows)
{
    IEnumerable<string> fields = dt.Columns.Cast<DataColumn>()
        .Select(col => col.DataType == typeof(DateTime)
            ? row.Field<DateTime>(col).ToString("yyyy/MM/dd hh:mm", inv) 
            : row.IsNull(col) ? "" : row[col].ToString());
    sb.AppendLine(string.Join(",", fields));
}

File.WriteAllText("filename.csv", sb.ToString());

You should choose a safer delimiter than comma.

This presumes that the type of the DataColumn is already DateTime(what it should be). If it's a string you have to parse it to DateTime first to be able to apply the desired format. Therefore use DateTime.Parse.

Upvotes: 1

Related Questions