简体   繁体   English

C# 从 SQL Server 更改日期格式

[英]C# changing date format from SQL Server

I'm relatively new to C#, SQL Server, and Stackoverflow.我对 C#、SQL Server 和 Stackoverflow 比较陌生。

I want the format of my date to stay the same from SQL Server to my C# code.我希望我的日期格式从 SQL Server 到我的 C# 代码都保持不变。 I have a screenshot of the SQL Server table:我有一张 SQL Server 表的截图:

sql表截图 . .

I just want the format to stay the same.我只希望格式保持不变。 I want the format to stay yyyy-mm-dd instead when I retrieve the data the format is dd/mm/yyyy 0:00:00 .当我检索数据时,我希望格式保持yyyy-mm-dd格式为dd/mm/yyyy 0:00:00

I then use the following code to retrieve the data from the server:然后我使用以下代码从服务器检索数据:

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;

I would expect the results in the ArrayList to be 2020-10-13 , instead I'm getting 10/11/2020 0:00:00 .我希望ArrayList的结果是2020-10-13 ,而不是我得到10/11/2020 0:00:00

I do not know why this happens for how to fix this.我不知道为什么会发生这种情况来解决这个问题。

You would do something like this:你会做这样的事情:

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

The ToString() function accepts a format string, so you can pretty much convert it to whatever format you want. ToString() 函数接受格式字符串,因此您几乎可以将其转换为您想要的任何格式。

More information here:更多信息在这里:

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

I found a previous post that helped me out a lot.我找到了以前的帖子,对我帮助很大。

Change date format in C# when reading from database and setting to label I needed to specify that the data being formatted was datatime rather than ToString() being called as an object. 从数据库读取并设置为标签时,在 C# 中更改日期格式我需要指定被格式化的数据是 datatime 而不是 ToString() 作为对象被调用。

Thanks EJ for putting me on the right track.感谢 EJ 让我走上正轨。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM