Bojensen Blogs

How to calculate date from week number

Axapta standard has a function called weekOfYear giving you the week number from a date. It doesn’t have a function to reverse it, but i do 😉

The function takes two arguments, year and week, and returns the date of the first day of that week.
Here you go:

static date Week2Date(int yr, int week)
{
    int     weekJan1st;
    int     dayJan1st;
    date    tempDate;
    #TimeConstants
    ;
    weekJan1st = wkofyr(dateStartYr(str2Date(strFmt(“%1-01-01”, yr), 321)));
    dayJan1st  = dayofwk(dateStartYr(str2Date(strFmt(“%1-01-01”, yr), 321)));
    tempDate   = dateStartYr(str2Date(strFmt(“%1-01-01”, yr), 321));
    switch(firstWeekOfYear())
    {
        case 0: // Starts on Jan 1
            tempDate -= (dayOfWk(tempDate) – 1);
            tempDate += (week – 1 ) * 7;
            break;
        case 1: // First full week
            //
            // If 1st Jan is a monday wkofyr gives correct result
            // If 1st Jan is a tuesday-thursday wkofyr gives one too much,
            // as this 4/5/6 day week is given it’s own week number.
            //
            if (dayJan1st != 1)
                tempDate += (8 – dayJan1st);
            tempDate += (week – 1) * 7;
            break;
        case 2: // First 4-day week
            if (mthofyr(tempDate) == 1 && weekOfYear(tempDate) > 50)
                tempDate += week * 7;
            else
                tempDate += (week – 1) * 7;
            tempDate -= (dayofwk(tempDate) – 1);
            break;
    }
    return tempDate;
}

Axapta Technet / Gangsta Software

Comments are closed.