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

我想知道两天之间的总天数:

1/1/2011
3/1/2011


RETURN
62

在 SQLServer 中可以做到吗?

420679 次浏览

SQLServerDateDiff

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);

你可以试试这个 MSDN 链路

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

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

这给出了两个日期之间午夜边界被跨越的次数。如果你把两个日期都包括在计数中,你可能会决定需要添加一个日期,或者如果你不想包括任何一个日期,就减去一个。

DateDiff:

DECLARE @startdate date = '2011/1/1'
DECLARE @enddate date = '2011/3/1'
SELECT DATEDIFF(day, @startdate, @enddate)
SELECT DATEDIFF(day, '2005-12-31 23:59:59.9999999', '2006-01-01 00:00:00.0000000');

另一种日期格式

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

如果你想做同样的事情存储过程,那么你需要应用下面的代码。

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

其中@FROM date 和@todate 是 SP 的参数

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*/

这是为我工作-

SELECT DATEDIFF(DAY, startdate, enddate) AS DayCount


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