开发者

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'开发者_Python百科) )-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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜