Get the week start date and week end date from week number
Straight to the SQL expressions to find the start (Monday) and end (Sunday) dates for a specific ISO week and year:
Week Start:
Week End:
Replace @Year
and @WeekNumber
. Adapt the 1
in 1 - DATEPART
if your weeks start on another day.
Behind the Scenes: A Deep Dive into SQL Date Arithmetic
It's Monday, So I Must Declare Variables
DATEADD and DATEPART are the power behind SQL Server's ability to play with dates. See them in action with a “week number” example, ensuring your query sits well with @@DATEFIRST
, SQL Server's week-start setting.
Using DATEPART and DATEADD for Precision Date Calculations
DATEPART retrieves a weekday as a number, helping us calculate days to add/subtract to align with week boundaries.
DATEADD shifts in time by adding or subtracting units (days, weeks, months, etc.) to a base date.
Variable Dates are Better Than Static Ones!
Maximize the flexibility by employing parameters or variable dates:
SQL's Got You Covered for Various DATEFIRST Settings
Ensure your script withstands different @@DATEFIRST
values. As DJ Khaled would say: "Always test – that's the major key!"
Example: Week 15 Start and End Dates (ISO Week Number System)
Specify Week 15 of 2023 and watch as SQL Server nimbly fetches the start and end dates:
No getting lost in time with concrete boundaries laid out for each week!
Tackling Non-standard Week Numbers and Leap Years
Leap Years Don't Have To Be a Leap of Faith!
Leap Years bring an extra day to the party. Test against a range of years (both leap and non-leap) to affirm the integrity of your solution. The code won't leap off a cliff, we promise!
Not All Week Number Systems are Born Equal
For non-standard week number systems, you'll need to adjust your calculations. Give your code a dose of notes and documentation to avoid surprising your successors or future self.
References
Was this article helpful?