 ShowAll Questionssorted byDate Posted Joseph Ferraro

# calculating iso week number

i know an apex method doesn't currently exist for calculating the iso week number, but does anyone have an algorithm i could use? Joseph Ferraro
FYI: I think this will do it...see source below
Code:
``` public static Integer DayOfWeek(Integer day, Integer month, Integer year) {
Double a = Math.floor((14 - month) / 12);
Double y = year - a;
Double m = month + 12 * a - 2;
Double myDouble1 = day + y + Math.floor(y / 4) - Math.floor(y / 100) + Math.floor(y / 400) + Math.floor((31 * m) / 12);
Integer myInt1 = myDouble1.intValue();
Integer myInt2 = 7;
Integer myInt3 = Math.mod(myInt1, myInt2);
return myInt3;
}

public static Double gregdaynumber(Integer year, Integer month, Integer day){
// computes the day number since 0 January 0 CE (Gregorian)
Integer y=year;
Integer m=month+1;
if(month < 3)
y=y-1;
if(month < 3)
m=m+12;
return Math.floor(365.25*y)-Math.floor(y/100)+Math.floor(y/400)+Math.floor(30.6*m)+day-62;
}

public Double isoweeknumber(Date d1){
Double isoweek;

Integer year = d1.year();
Integer month = d1.month() - 1;
Integer day = d1.day();
Integer wday = DayOfWeek(day, month, year);
System.debug('the weekday is:' + wday);

wday = Math.mod((wday+6),7) + 1; // weekdays will be numbered 1 to 7

Integer yiso = year;

Double d0 = gregdaynumber(year,1,0);
Double wday0 = Math.mod((d0+4).intValue(),7) + 1;

Double d = gregdaynumber(year,month+1,day);
Double wniso = Math.floor((d-d0+wday0+6)/7)-Math.floor((wday0+3)/7);

// check whether the last few days of December belong to the next year's ISO week

if((month == 11) && ((day-wday) > 27)){
wniso=1;
yiso=yiso+1;
}

// check whether the first few days of January belong to the previous year's ISO week

if((month == 0) && ((wday-day) > 3)){
d0=gregdaynumber(year-1,1,0);
wday0=Math.mod((d0+4).intValue(),7) + 1;
wniso=Math.floor((d-d0+wday0+6)/7)-Math.floor((wday0+3)/7);
yiso=yiso-1;
}

return wniso;
}```