0

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".

1
  • Can you please show your work as well? Example of input and output as well. Commented Jun 2, 2015 at 7:22

1 Answer 1

1

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.

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

Comments

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.