Click here to Skip to main content
Click here to Skip to main content

Useful DateTime Functions

By , 1 Sep 2011
 
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)

About the Author

db_developer
Database Developer Freelancer
Ukraine Ukraine
Member
MS SQL Server Database Developer with 7+ years experience
 
Technologies/languages: Business Intelligence, SQL, MDX, VBA, SQL Server, Analysis Services (SSAS), Reporting services (SSRS), Integration Services (SSIS), DataWarehouse.
Also: economic background.
 
Feel free to contact me for rates and details.

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
Hint: For improved responsiveness ensure Javascript is enabled and choose 'Normal' from the Layout dropdown and hit 'Update'.
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
-- There are no messages in this forum --
Permalink | Advertise | Privacy | Mobile
Web01 | 2.6.130516.1 | Last Updated 1 Sep 2011
Article Copyright 2011 by db_developer
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid