如何从DATETIME列获取DATE?

时间:2015-04-16 08:54:02

标签: sql asp.net datetime sql-server-2005

我想从DateTime列获取日期。

<asp:SqlDataSource ID="SqlDataSource1" runat="server" 
ConnectionString="<%$ ConnectionStrings:ConnectionString %>" 
SelectCommand="SELECT [name], [book_id], [book_name], [taken_date], [last_date], [renewed_date], [status], [comment], [fine_amount] FROM [library] WHERE ([admn_no] = @admn_no)">
<SelectParameters>
   <asp:ControlParameter ControlID="TextBox1" Name="admn_no" PropertyName="Text" 
   Type="String" />
</SelectParameters>
</asp:SqlDataSource>

从以上这些 [taken_date][last_date][renewed_date] 列显示日期和时间

  

(例如:4/14/2015 12:00:00 AM)。

如何仅显示日期

  

(例如:4/14/2015)?

1 个答案:

答案 0 :(得分:5)

您可以将CAST(column_name AS DATE)用于Sql-server 2008及以上版本

SELECT [name], [book_id], [book_name], 
cast([taken_date] as date) as [taken_date], 
cast([last_date] as date) as [last_date], 
cast([renewed_date] as date) as [renewed_date], 
[status], [comment], [fine_amount] 
FROM [library] WHERE ([admn_no] = @admn_no)

编辑1

对于sqlserver 2008之前的早期版本,你可以像

那样做
SELECT CONVERT(VARCHAR(10),GETDATE(),111)

所以整个查询就像这样

SELECT [name], [book_id], [book_name], 
CONVERT(VARCHAR(10),[taken_date],111) as [taken_date], 
CONVERT(VARCHAR(10),[last_date],111) as [last_date], 
CONVERT(VARCHAR(10),[renewed_date],111) as [renewed_date], 
[status], [comment], [fine_amount] 
FROM [library] WHERE ([admn_no] = @admn_no)

编辑2

将日期格式从yyyy/dd/mm格式化为dd/mm/yyyy,您可以更改为101而不是111

SELECT CONVERT(VARCHAR(10),GETDATE(),101)

所以查询将是

SELECT [name], [book_id], [book_name], 
CONVERT(VARCHAR(10),[taken_date],101) as [taken_date], 
CONVERT(VARCHAR(10),[last_date],101) as [last_date], 
CONVERT(VARCHAR(10),[renewed_date],101) as [renewed_date], 
[status], [comment], [fine_amount] 
FROM [library] WHERE ([admn_no] = @admn_no)