2009-12-14 151 views
1

我使用SQL Server 2005的ASP.NET。從數據庫的日期字段更改日期格式

我的日期保存在數據庫中,數據類型=「smalldatetime」。

我顯示日期值到名爲txtDate與讀者的文本框......

Dim conn As Data.SqlClient.SqlConnection 
    Dim Comm As Data.SqlClient.SqlCommand 
    Dim reader As Data.SqlClient.SqlDataReader 

    conn = New Data.SqlClient.SqlConnection(..............) 

    Comm = New Data.SqlClient.SqlCommand(_ 
    ("SELECT * FROM Table1 WHERE Age = 88"), conn) 

    conn.Open() 

    reader = Comm.ExecuteReader() 

    If reader.Read() Then 

     txtDate.Text = reader.Item("theDate").ToString 

    End If 

    reader.Close() 
    conn.Close() 

但目前我得到的日期顯示爲「2008/06/30 12:00:00 AM「,我想把它顯示爲」2008年6月30日「。

這怎麼辦?

回答

1

數據如何存儲在數據庫中是無關緊要的 - 您將在客戶端代碼中獲得DateTime。然後,只需要格式化即可。

嘗試是這樣的:

If reader.Read() Then 
    Dim date as DateTime = CType(reader.Item("theDate"), DateTime) 
    txtDate.Text = date.ToString("dd MMMM yyyy") 
End If 

這裏的「DD」表示「月日」,「MMMM」的意思和「YYYY」「年滿一個月」的意思是「四位數年份」 。

有關更多詳細信息,請參見MSDN on custom date and time format strings。或者,您可以使用standard date and time format string這將考慮到您目前的文化。 (自定義的將考慮到每個單獨的字段,因此月份名稱將適合於文化,但格式字段的順序和樣式由格式字符串固定。)

2

ToString("dd MMMM yyyy")替換ToString。您可能希望在MSDN中查看DateTime.ToString的重載和日期時間格式化字符串。

與您的代碼的其他點 - 如果你真的是從一個單一的行選擇一個值,然後限制你的選擇列表(即不使用SELECT *),並考慮使用的ExecuteScalar而不是的ExecuteReader ...

+0

txtDate.Text = reader.Item( 「theDate」)的ToString( 「DD MMMM YYYY」)做了不適合我,但上面的答案是。謝謝你的幫助。 – Etienne 2009-12-14 08:22:56

0

您應該使用數據格式爲字符串。

將您的值將reader.Item(「theDate」)轉換爲DateTime對象並使用ToString方法。

yourDateTime.ToString("dd MMMM yyyy"); 

看一看這些

+0

MMM會給Jun而不是6月,至少在不變的文化中。 – 2009-12-14 08:18:10

+0

是的,真的會改變這一點。 – 2009-12-14 08:19:20