How to return only the Date from a SQL Server DateTime datatype

SELECT GETDATE()

Returns: 2008-09-22 15:24:13.790

I want that date part without the time part: 2008-09-22 00:00:00.000

How can I get that?


On SQL Server 2008 and higher, you should CONVERT to date:

SELECT CONVERT(date, getdate())

On older versions, you can do the following:

SELECT DATEADD(dd, 0, DATEDIFF(dd, 0, @your_date))

for example

SELECT DATEADD(dd, 0, DATEDIFF(dd, 0, GETDATE()))

gives me

2008-09-22 00:00:00.000

Pros:

  • No varchar <-> datetime conversions required
  • No need to think about locale

  • SQLServer 2008 now has a 'date' data type which contains only a date with no time component. Anyone using SQLServer 2008 and beyond can do the following:

    SELECT CONVERT(date, GETDATE())
    

    如果使用SQL 2008及以上版本:

    select cast(getdate() as date)
    
    链接地址: http://www.djcxy.com/p/2756.html

    上一篇: 如何检查SQL Server表中是否存在列?

    下一篇: 如何仅从SQL Server DateTime数据类型返回日期