SQL SERVER:获取两个日期之间的总天数


146

我正在尝试获取两天之间的总天数:

1/1/2011
3/1/2011

RETURN
62

在SQL Server中可以做吗?


2
在当前日历中,介于 1/1和3/1 之间的天数永远不会返回62。它会返回58或59。即使您包括开始日期和结束日期,也将是60或
61。– TylerH

7
如果您不在美国,它将返回2天。
MGOwen

Answers:


287

PRINT DATEDIFF(DAY, '1/1/2011', '3/1/2011') 会给你你想要的。

这给出了两个日期之间的午夜边界越过的次数。如果您将两个日期都包括在计数中,则可能决定需要对此添加一个-如果不想包含两个日期,则减去一个。


正如我在结果中看到的那样,它还会进行datetime和datetime2的处理。
Honza P.

39

SQL Server DateDiff

DECLARE @startdate datetime2 = '2007-05-05 12:10:09.3312722';
DECLARE @enddate datetime2 = '2009-05-04 12:10:09.3312722'; 
SELECT DATEDIFF(day, @startdate, @enddate);

17

您可以尝试此MSDN链接

DATEDIFF ( datepart , startdate , enddate )
SELECT DATEDIFF(DAY, '1/1/2011', '3/1/2011')

16

参见DateDiff

DECLARE @startdate date = '2011/1/1'
DECLARE @enddate date = '2011/3/1'
SELECT DATEDIFF(day, @startdate, @enddate)

12

其他日期格式

select datediff(day,'20110101','20110301')

4
SELECT DATEDIFF(day, '2005-12-31 23:59:59.9999999', '2006-01-01 00:00:00.0000000');

0

这对我有用-

SELECT DATEDIFF(DAY, startdate, enddate) AS DayCount

Example : SELECT DATEDIFF(DAY, '11/30/2019', GETDATE()) AS DayCount

-1

如果要执行存储过程相同的操作,则需要应用以下代码。

select  (datediff(dd,'+CHAR(39)+ convert(varchar(10),@FromDate  ,101)+ 
 CHAR(39)+','+CHAR(39)+ convert(varchar(10),@ToDate  ,101) + CHAR(39) +')) 
 Daysdiff

其中@fromdate和@todate是SP的参数


-1
DECLARE @FDate DATETIME='05-05-2019' /*This is first date*/
 GETDATE()/*This is Current date*/
SELECT (DATEDIFF(DAY,(@LastDate),GETDATE())) As DifferenceDays/*this query will return no of days between firstdate & Current date*/

2
你能解释一下你的答案吗?仅代码的答案通常很难解释。
乔丹·卡斯珀
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.