public Integer weekOfMonth(Date todaysDate){ Integer weekCount = 0; Integer startWeekResidue = 0; Integer endWeekResidue = 0; //Calculating startWeekResidue Date dt = todaysDate.toStartOfMonth().addDays(-1); Date dtFirstWeekend = dt.toStartOfWeek().addDays(6); startWeekResidue = dt.daysBetween(dtFirstWeekend); //Calculating endWeekResidue Date dtLastWeekend = todaysDate.toStartOfWeek().addDays(-1); endWeekResidue = dtLastWeekend.daysBetween(todaysDate); //Counting the weeks weekCount = (todaysDate.day() - (startWeekResidue + endWeekResidue))/7; weekCount += (startWeekResidue > 0 ? 1:0)+(endWeekResidue > 0 ? 1:0); System.Debug('Week Number: ' + weekCount); return weekCount; }
Example: Pass Parameter: 13Sept2017 – Output: 3