Home > Software design >  When Exporting from sql to Csv -> How I change date format
When Exporting from sql to Csv -> How I change date format

Time:03-31

I made my small project(c# app)your text, which export data from sql database into the csv file. I would like to change date format from | 10.01.2022 to -> 2022.01.10.

Thanks for help.

Regards,

vit

using System.Data;
using System.Data.SqlClient;

namespace ExtractApp
{
    class Program
    {
        static void Main(string[] args)
        {
            GetCSV();

        }

        private static string GetCSV()
        {
            using (SqlConnection cn = new SqlConnection(GetConnectionString()))
            {
                cn.Open();
                return CreateCSV(new SqlCommand("Select * from [reports].[xxx]", cn).ExecuteReader());
                cn.Close();
                
            }

        }

        private static string CreateCSV(IDataReader reader)
        {
            string file = "C:\\SqlToCsv\\Data.csv";
            List<string> lines = new List<string>();

            string headerLine = "";
            if (reader.Read())
            {
                string[] columns = new string[reader.FieldCount];
                for (int i = 0; i < reader.FieldCount; i  )
                {
                    columns[i] = reader.GetName(i);
                   

                }
                headerLine = string.Join(",", columns);
                lines.Add(headerLine);

            }

            //data
            while (reader.Read())
            {
                object[] values = new object[reader.FieldCount];
                reader.GetValues(values);
                lines.Add(string.Join(",", values));
            }

            //file
            System.IO.File.WriteAllLines(file, lines);

            return file;
            
        }

    }
}

CodePudding user response:

Since your column type is Date, it will be mapped to a DateTime (docs) in C#, so we can use pattern matching to get the DateTime and convert it to a string with the .ToString method:

object[] values = new object[reader.FieldCount];
reader.GetValues(values);

for (int i = 0; i < values.Length;   i)
{
    if (values[i] is DateTime dateTimeValue)
    {
        values[i] = dateTimeValue.ToString("yyyy.MM.dd", System.Globalization.CultureInfo.InvariantCulture);
    }
}
lines.Add(string.Join(",", values));

More info:

  • Related