T-SQL to trim a datetime to the nearest date?

旧时模样 提交于 2019-12-08 14:40:04

问题


Duplicate of What's the BEST way to remove the time portion of a datetime value (SQL Server)?

I have a column that tracks when things are created using a datetime, but I'd like to generate a report that groups them by day, so I need a way of nulling out the time component of a datetime column.

How do I do this?


回答1:


One way is to change getdate() to your column name,

select dateadd(dd, datediff(dd, 0, getdate())+0, 0)



回答2:


Why not convert straight to date:

select convert(date, getdate())

This truncates days, not rounds. To round Days do this:

select convert(date, getdate() + 0.5)



回答3:


Here's another solution:

SELECT CAST( FLOOR( CAST( GETDATE() AS float) ) AS smalldatetime)



回答4:


This is a simple way to get the date (as a string) from a datetime:

convert(varchar, <the date field/value/etc>, 101)

But note that ordering on this field will be alphabetical rather than by date since it's now a string




回答5:


Yes. There are many formats to choose from so I'll link it instead.

http://library.cirr.com/Microsoft/SQL-Server-v7/html/ca-co_1.htm

If you wish to zero out the time like your post implies, you can try this:

select cast(convert(varchar, getdate(), 101) as datetime)



回答6:


declare @CurrentDate datetime
set @CurrentDate = dateadd(dd, datediff(dd, 0, getdate()), 0)

--or--

select dateadd(dd, datediff(dd, 0, MyDateColumn), 0) as DateOnly
from tblX



回答7:


In my searches I came across the following solution, it strips time out of UTC time only, but I found it interesting, so I thought someone else would too:

FUNCTION TrimDate(@dt AS DATETIME) RETURNS DATETIME
BEGIN
    RETURN CAST(CAST((@dt - 0.500000038580247) AS INT) AS DATETIME) 
END

I would presume that it runs quickly since all it's doing is rounding and casting.




回答8:


I simply do cast(getdate() as date)



来源:https://stackoverflow.com/questions/538412/t-sql-to-trim-a-datetime-to-the-nearest-date

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!