Thursday, August 30, 2007

Find date using year and week as input

Today we needed an algorithm to calculate a date using only a year and a week number as input. As you may know different parts of the world has different rules for what week to consider as the first week of the year, so you have to be very careful when trying to write a generic algorithm.

In stead of being clever and figure this out ourselves, we decided that “AX knows best”. So basically we produce some dates and let AX tell us if they are in the week we are looking for.
The only part where we try to be clever is where we figure out what date to start asking on and not just start in the beginning of the year.

Here is what we came up with:
static void Week2Ddate(Args _args)
Week week = 1;
Yr yr = 2009;

Date testDate = dateStartYr(mkDate(01, 01, yr)) + ((week - 1) * 7);
Int weekdays;

if (weekOfYear(testDate) != week)
if (week > weekOfYear(testDate))
weekdays = 7;
weekdays = -7;

while (weekOfYear(testDate) != week)
testDate = testDate + weekdays;

info (strFmt("Dato: %1", dateStartWk(testDate)));

Any comments with better ideas are welcome. And well, in the end of the day we found that we didn't need the algorithm anyway, but it was fun to think about how to do it.


Jan B. Kjeldsen said...

Why so complicated?
How do format code on blogger?

static date week2date(Yr yr, Week week, Days day = 1)
date date1 = mkDate(01,01,yr);
Days d1 = dayOfWk(date1);
return (d1 <= 4 ? date1 - d1 : date1 - d1 + 7) + 7*(week - 1) + day;

Palle Agermark said...

Looks good, but do you handle the fact taht different regions of th world has different ways of dertiminig which week is week 1?

I use the HTML tag PRE to format code. I haven't really looked into if I can change the CSS, but for now it is good enough.