1

What is the best way to take a date variable in SQL and set it to Beginning of Year and End of Year?

declare @calcDate date = '7/7/2016'

How do I get '1/1/2016' and '12/31/2016' using @calcDate?

Tim Lehner
  • 14,813
  • 4
  • 59
  • 76
Anagins
  • 13
  • 2

3 Answers3

2

I would just use datefromparts():

select datefromparts(year(@calcdate), 1, 1) as soy,
       datefromparts(year(@calcdate), 12, 31) as eoy

Earlier versions of SQL Server require strange date arithmetic. This function is available in SQL Server 2012+ (see here).

Gordon Linoff
  • 1,242,037
  • 58
  • 646
  • 786
1
DECLARE @calcDate date = '7/7/2016'

SELECT
DATEADD(yy, DATEDIFF(yy,0,@calcDate), 0) AS BeginningOfYear,
DATEADD(yy, DATEDIFF(yy,0,@calcDate) + 1, -1) AS EndOfYear
freakinthesun
  • 699
  • 1
  • 9
  • 19
  • This answer looks right why the down vote with no comment? – Dave Kelly Jul 07 '16 at 17:33
  • @DaveKelly Not my downvote, but this answer was posted when there were no tags about the RDBMS, so it could've been wrong for op. In this case, it wasn't – Lamak Jul 07 '16 at 17:34
0

Seems to me there is no real "calculation" to be done here since the first day of the year is always 1/1 and the last day is always 12/31. We just need to append these to the year in question:

declare @calcDate date = '7/7/2016'
select cast(cast(year(@calcDate) as varchar(4)) + '0101' as date)
select cast(cast(year(@calcDate) as varchar(4)) + '1231' as date)

Result:

2016-01-01
2016-12-31

year is available in SQL Server 2008 and above.

Tim Lehner
  • 14,813
  • 4
  • 59
  • 76