Although I'd consider this technique very dirty, for months it does work. This is because there are always 12 months in a year.
For weeks it's both dirty and flawed. Some years have more weeks than others, because some weeks span more than one year.
I would recommend instead just using DATEDIFF()
.
Depending on the day-of-week that you want your weeks to start on, you need to do a little bit of calculation...
- Sun as start of week = DATEDIFF(WEEK, -1, yourDate )
- Mon as start of week = DATEDIFF(WEEK, -1, yourDate-1)
- Tue as start of week = DATEDIFF(WEEK, -1, yourDate-2)
- Wed as start of week = DATEDIFF(WEEK, -1, yourDate-3)
- Thu as start of week = DATEDIFF(WEEK, -1, yourDate-4)
- Fri as start of week = DATEDIFF(WEEK, -1, yourDate-5)
- Sat as start of week = DATEDIFF(WEEK, -1, yourDate-6)
I also recommend using this for your month calculations. DATEDIFF(MONTH, <a base date>, <your date>)
, the current one is really clunky.
EDIT Examples to turn the values above back into DATETIME
- Sun as start of week = DATEADD(WEEK, DATEDIFF(WEEK, -1, yourDate ), -1 )
- Mon as start of week = DATEADD(WEEK, DATEDIFF(WEEK, -1, yourDate-1), -1+1)
- Tue as start of week = DATEADD(WEEK, DATEDIFF(WEEK, -1, yourDate-2), -1+2)
- Wed as start of week = DATEADD(WEEK, DATEDIFF(WEEK, -1, yourDate-3), -1+3)
- Thu as start of week = DATEADD(WEEK, DATEDIFF(WEEK, -1, yourDate-4), -1+4)
- Fri as start of week = DATEADD(WEEK, DATEDIFF(WEEK, -1, yourDate-5), -1+5)
- Sat as start of week = DATEADD(WEEK, DATEDIFF(WEEK, -1, yourDate-6), -1+6)