简体   繁体   中英

Datetime in SQL Server and C#

I have this simple query

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

The result is 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

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

How can I achieve that with C# code ?

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 .

What you need is the textual format of this:

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

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

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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