【问题标题】:When Exporting from sql to Csv -> How I change date format从 sql 导出到 Csv 时 -> 如何更改日期格式
【发布时间】:2022-07-20 23:22:37
【问题描述】:

我做了我的小项目(c# app)your text,它将数据从 sql 数据库导出到 csv 文件。 我想从 | 更改日期格式10.01.2022 至 -> 2022.01.10.

感谢您的帮助。

问候,

维生素

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;
            
        }

    }
}

【问题讨论】:

  • 您是否使用日期时间类型将这些日期存储在您的数据库中?
  • 只是约会
  • 您使用的是哪个 dbms?
  • 微软 sql 服务器管理 2018

标签: c# sql date format export-to-csv


【解决方案1】:

由于你的列类型是Date,它会在C#中映射到DateTimedocs),所以我们可以使用模式匹配来获取DateTime并将其转换为string .ToString 方法:

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));

更多信息:

【讨论】:

  • 我应该只添加这部分代码吗?或者它不是我代码中的 (for)?
  • @FallenDraZy 在while (reader.Read()) 循环中代替您当前的代码。
【解决方案2】:

你可以用sql语法编写它; 比如日期字段的名称是:created_date

在 sql 中,您可以通过以下方式更改其格式:

`Select DATE_FORMAT(created_date, "%M.%m.%d"), other_fields then your condition ` 

玩得开心……

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-12-06
    • 2021-03-12
    • 1970-01-01
    • 1970-01-01
    • 2017-07-12
    • 1970-01-01
    • 1970-01-01
    • 2013-03-30
    相关资源
    最近更新 更多