简体   繁体   English

SQL Server 2005中DATETIME的DATE(不使用VARCHAR)

[英]DATE from DATETIME in SQL SERVER 2005 (Without using VARCHAR)

Our application using SQL SERVER 2005 我们的应用程序使用SQL SERVER 2005

I need to show only DATE from DateTime in GridView. 需要显示GridView中DateTime的DATE

I don't want to convert it into any other format like Varchar or something. 我不想转换为任何其他格式,例如Varchar或其他格式。 It should be only in DateTime format itself, without Time . 它本身只能是DateTime格式,不能带有Time

Please Help. 请帮忙。

In SQL Server, the code is 在SQL Server中,代码为

CAST(datediff(d,0,datetimecol) as datetime)

However, I doubt that does any good for a GridView, which will infer it to be a "datetime" column and show a "date + time" formatting, even if the times are ALL "00:00:00". 但是,我怀疑这对GridView是否有好处,即使时间为ALL“ 00:00:00”,它也会将其推断为“ datetime”列并显示“ date + time”格式。

Bound the DateField coloumn in Grid like below, then it works... 像下面这样在网格中绑定DateField列,然后它可以工作...

<asp:BoundField DataField="Your_Date_Column" 
                    HeaderText="Date_Column" 
                    DataFormatString="{0:d}" />

DataFormatString="{0:d}" it display the Date like 3/11/2013 DataFormatString="{0:d}"它显示日期,如3/11/2013

In SQL 2005 there is no way of keeping it in datetime format without the time (time is part of the datetime type), the best you could get would be something like: 在SQL 2005中,没有时间就无法将其保持在datetime格式中(time是datetime类型的一部分),您可以获得的最佳结果是:

2013-04-02 00:00:00.000

If you were willing to convert to VARCHAR, you could use something similar to: 如果您愿意转换为VARCHAR,则可以使用类似以下内容的方法:

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

Which would display the date portion as you want it. 它将根据需要显示日期部分。 Otherwise, you need to move to SQL 2008+ where there is a proper date type that you can use instead. 否则,您需要移动到SQL 2008+,那里有可以使用的正确日期类型。

If you need to stick with SQL 2005, the best way to achive this is to just format it in the datagrid view itself. 如果您需要坚持使用SQL 2005,最好的方法是在datagrid视图本身中对其进行格式化。

If you want to truncate a datetime so that it only returns the date as at midnight, see the accepted answer to this question - the question relates specifically to SQLServer 2008, but the answer includes details of how to achieve this in SQLServer 2005. 如果要截断日期时间,使其仅返回午夜的日期,请参阅此问题的可接受答案-该问题专门与SQLServer 2008有关,但答案包括有关如何在SQLServer 2005中实现此问题的详细信息。

If you want to convert a datetime field into a date-only field - you cannot achieve this in SQLServer 2005 in SQL alone, as there is no date-only datatype - see here . 如果要将datetime字段转换为仅日期的字段-您不能仅在SQL Server 2005中使用SQL来实现此目的,因为没有仅日期的数据类型-请参见此处

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

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