TaylorOtwell
TaylorOtwell

Reputation: 7337

Calculating corresponding calendar day of previous years

I have the following beast of an SQL (DB2) statement...

select ((date(days(date(cast(year('2012-03-28')-6 as char(4))|| '-01-01')) -(dayofweek(date(cast(year('2012-03-28')-6 as char(4))|| '-01-01') )-1))+7 days)+(((week('2012-03-28')-2)* 7)+dayofweek('2012-03-28')-1) days) AS CAL_COMP_DATE
from sysibm.sysdummy1

Taking the input date of Wednesday, 2012-03-28, this would return Wednesday, 2006-03-29. Notice that it matched the Thursdays. It matches the corresponding calendar day of previous years.

Is there a more elegant way of accomplishing the same goal in C# or VB.NET? I've tried translating this query into VB.NET, but haven't been able to do so perfectly and it just looks horrible and unmaintainable.

Upvotes: 0

Views: 527

Answers (1)

Daniel Hilgarth
Daniel Hilgarth

Reputation: 174309

I don't completely understand the rule for finding that day. But you could use something along these lines:

var originalDate = new DateTime(2012,03,28);
var newDate = originalDate.AddYears(-6);
var daysToAdd = originalDate.DayOfWeek - newDate.DayOfWeek;
if(daysToAdd < -3)
    daysToAdd += 7;
if(daysToAdd > 3)
    daysToAdd -= 7;
newDate = newDate.AddDays(daysToAdd);

This always rounds to the nearest day with the same DayOfWeek.

Upvotes: 3

Related Questions