你如何计算两个日期之间的周数?

时间:2010-03-29 14:10:51

标签: tsql

如何计算两个日期之间的周数?

例如如下

Declare @StartDate as DateTime = "01 Jan 2009";
Declare @EndDate as DateTime = "01 June 2009";

@StartDate and @EndDate

2 个答案:

答案 0 :(得分:15)

使用Datediff功能。 datediff(ww,@startdate,@enddate)

ww告诉函数你需要用哪些单位计算差值。

http://msdn.microsoft.com/en-us/library/ms189794.aspx

答案 1 :(得分:2)

您可以使用以下功能检索两个日期之间的周数:

CREATE FUNCTION [dbo].[fGetWeeksList]
(
    @StartDate DATETIME 
   ,@EndDate DATETIME 
)
RETURNS 
TABLE 
AS
RETURN
(

SELECT DATEADD(DAY,-(DATEPART(DW,DATEADD(WEEK, x.number, @StartDate))-2),DATEADD(WEEK, x.number, @StartDate)) as [StartDate]
      ,DATEADD(DAY,-(DATEPART(DW,DATEADD(WEEK, x.number + 1, @StartDate))-1) ,DATEADD(WEEK, x.number + 1, @StartDate)) AS [EndDate]
FROM master.dbo.spt_values x
WHERE x.type = 'P' AND x.number <= DATEDIFF(WEEK, @StartDate, DATEADD(WEEK,0,CAST(@EndDate AS DATE)))