首页 > 解决方案 > C# 从 SQL Server 更改日期格式

问题描述

我对 C#、SQL Server 和 Stackoverflow 比较陌生。

我希望我的日期格式从 SQL Server 到我的 C# 代码保持不变。我有一个 SQL Server 表的屏幕截图:

sql表截图.

我只是希望格式保持不变。yyyy-mm-dd当我检索格式为 的数据时,我希望格式保持不变dd/mm/yyyy 0:00:00

然后我使用以下代码从服务器检索数据:

ArrayList a = new ArrayList(); 
DataTable d = new DataTable();         
string sql = "SELECT * FROM myServer";

MySql.Data.MySqlClient.MySqlCommand cmd = new MySql.Data.MySqlClient.MySqlCommand(sql, conn);
MySqlDataAdapter myA = new MySqlDataAdapter(cmd);

myA.Fill(d);
cmd.ExecuteNonQuery();

foreach (DataRow row in d.Rows)
{
    FitnessManager f = new FitnessManager();
    f.testDate = row["testDate"].ToString();
    f.tDate = row["tDate"].ToString();
    f.dtDate = row["dtDate"].ToString(); 
    a.Add(f);
}

return a;

我希望结果ArrayList2020-10-13,而不是我得到10/11/2020 0:00:00

我不知道为什么会发生这种情况,如何解决这个问题。

标签: c#sql

解决方案


你会做这样的事情:

  f.tDate = row["tDate"].ToString("yyyy-MM-dd")

ToString() 函数接受格式字符串,因此您几乎可以将其转换为您想要的任何格式。

更多信息在这里:

https://docs.microsoft.com/en-us/dotnet/standard/base-types/custom-date-and-time-format-strings


推荐阅读