SQL Server和C#中的日期时间

时间:2021-05-14 08:52:18

I have this simple query

我有这个简单的查询

insert into my_table(date) values(getdate())

The result is 2017-01-05 12:41:37.273.

结果是2017-01-05 12:41:37.273。

I want when I do

我想要的时候

select * 
from my_table

from my Windows Forms application to set the label1.text = 5 Thu 12:41

从我的Windows窗体应用程序设置label1.text = 5 Thu 12:41

2017-01-05 12:41:37.273 ----> 5 Thu 12:41

How can I achieve that with C# code ?

如何使用C#代码实现这一目标?

3 个解决方案

#1


3  

Assuming that you read the data from SQL Server into your C# application I'm pretty sure, that a column of sql type DATETIME will be mapped to a C# type DateTime.

假设您将SQL Server中的数据读入C#应用程序,我很确定,一列sql类型的DATETIME将映射到C#类型的DateTime。

What you need is the textual format of this:

你需要的是这个文本格式:

DateTime d = DateTime.Now;
MessageBox.Show(d.ToString("d ddd HH:mm")); 

#2


1  

You can parse string to DateTime and wrtie your own format.

您可以将字符串解析为DateTime并使用自己的格式。

  DateTime myDateTime = DateTime.Parse("2017-01-05 12:41:37");
  string formatedDateTime = myDateTime.ToString("dd-mm-yyyy");

#3


0  

From SQL you can you the below format to get your expected result:

从SQL您可以使用以下格式来获得预期结果:

SELECT CAST(DATEPART(D, GETDATE()) AS VARCHAR(2)) + ' ' + 
       LEFT(DATENAME(WEEKDAY, GETDATE()), 3) + ' ' + 
       LEFT(CONVERT(VARCHAR(8), GETDATE(), 108), 5)

-- Output: 5 Thu 05:22

#1


3  

Assuming that you read the data from SQL Server into your C# application I'm pretty sure, that a column of sql type DATETIME will be mapped to a C# type DateTime.

假设您将SQL Server中的数据读入C#应用程序,我很确定,一列sql类型的DATETIME将映射到C#类型的DateTime。

What you need is the textual format of this:

你需要的是这个文本格式:

DateTime d = DateTime.Now;
MessageBox.Show(d.ToString("d ddd HH:mm")); 

#2


1  

You can parse string to DateTime and wrtie your own format.

您可以将字符串解析为DateTime并使用自己的格式。

  DateTime myDateTime = DateTime.Parse("2017-01-05 12:41:37");
  string formatedDateTime = myDateTime.ToString("dd-mm-yyyy");

#3


0  

From SQL you can you the below format to get your expected result:

从SQL您可以使用以下格式来获得预期结果:

SELECT CAST(DATEPART(D, GETDATE()) AS VARCHAR(2)) + ' ' + 
       LEFT(DATENAME(WEEKDAY, GETDATE()), 3) + ' ' + 
       LEFT(CONVERT(VARCHAR(8), GETDATE(), 108), 5)

-- Output: 5 Thu 05:22