Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / database / SQL-Server

Useful DateTime Functions

4.00/5 (1 vote)
1 Sep 2011CPOL 7.1K  
IF OBJECT_ID (N'dbo.GetIntervalStartDate', N'FN') IS NOT NULL DROP FUNCTION dbo.GetIntervalStartDate;GO--gets first day of interval date belongs toCREATE FUNCTION dbo.GetIntervalStartDate (@Date datetime,@IntervalType int = 0--0 - DAY, 1 - WEEK (Mon to Sun), 2 - MONTH, 3 -...
SQL
IF OBJECT_ID (N'dbo.GetIntervalStartDate', N'FN') IS NOT NULL
    DROP FUNCTION dbo.GetIntervalStartDate;
GO
--gets first day of interval date belongs to
CREATE FUNCTION dbo.GetIntervalStartDate (
@Date datetime
,@IntervalType int = 0
--0 - DAY, 1 - WEEK (Mon to Sun), 2 - MONTH, 3 - FYQUARTER, 4 - FYQUARTER
)
RETURNS datetime2
AS
BEGIN
    DECLARE @IntervalStartDate datetime;
    
    SELECT @IntervalStartDate = 
     
	(case @IntervalType
		when 0 then DATEADD(dd,DATEDIFF(dd,0,@Date),0)		--First Day of Current Day
		when 1 then DATEADD(wk,DATEDIFF(wk,0,@Date),0)		--First Day of Current Week
		when 2 then DATEADD(mm,DATEDIFF(mm,0,@Date),0)		--First Day of Current Month'
		when 3 then DATEADD(qq,DATEDIFF(qq,0,@Date),0)		--First Day of Current Quarter
		when 4 then DATEADD(qq,DATEDIFF(qq,0,@Date),0)		--First Day of Current Quarter
		else NULL
	end);
     
	RETURN(@IntervalStartDate);
END;
GO

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)