SQL 如何在SQL中选择没有时间的日期

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5125609/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-01 09:28:27  来源:igfitidea点击:

How to select date without time in SQL

sqlsql-serversql-server-2005

提问by Neeraj

When I select date in SQL it is returned as 2011-02-25 21:17:33.933. But I need only the Date part, that is 2011-02-25. How can I do this?

当我在 SQL 中选择日期时,它返回为 2011-02-25 21:17:33.933. 但我只需要 Date 部分,即2011-02-25. 我怎样才能做到这一点?

采纳答案by bernd_k

I guess he wants a string.

我猜他想要一根绳子。

select convert(varchar(10), '2011-02-25 21:17:33.933', 120)

120 here tells the convert function that we pass the input date in the following format: yyyy-mm-dd hh:mi:ss.

这里的 120 告诉转换函数我们以以下格式传递输入日期:yyyy-mm-dd hh:mi:ss.

回答by Prad9

回答by RichardTheKiwi

The fastest is datediff, e.g.

最快的是datediff,例如

select dateadd(d, datediff(d,0, [datecolumn]), 0), other..
from tbl

But if you only need to use the value, then you can skip the dateadd, e.g.

但是如果您只需要使用该值,那么您可以跳过 dateadd,例如

select ...
WHERE somedate <= datediff(d, 0, getdate())

where the expression datediff(d, 0, getdate())is sufficient to return today's date without time portion.

其中表达式datediff(d, 0, getdate())足以返回没有时间部分的今天的日期。

回答by Anna-leny

Use CAST(GETDATE() as date) that worked for me, simple.

使用对我有用的 CAST(GETDATE() 作为日期),很简单。

回答by A.Goutam

you can use like this

你可以这样使用

SELECT Convert(varchar(10), GETDATE(),120) 

回答by Domcha

For 2008 older version:

对于2008 旧版本

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

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

回答by Ram Pratap

You can try this one too.

你也可以试试这个。

SELECT CONVERT(DATE, GETDATE(), 120)

回答by RollRoll

Convert it back to datetime after converting to date in order to keep same datatime if needed

转换为日期后将其转换回日期时间,以便在需要时保持相同的数据时间

select Convert(datetime, Convert(date, getdate())  )

回答by Simon Alphonse

In case if you need the time to be zeros like 2018-01-17 00:00:00.000:

如果您需要时间为零,例如2018-01-17 00:00:00.000

SELECT CONVERT(DATETIME, CONVERT(DATE, GETDATE()), 121)

SELECT CONVERT(DATETIME, CONVERT(DATE, GETDATE()), 121)