Monday, April 4, 2011

Calculate number of week from a date in Apex

I had to calculate number of week of the year based on a date field so i came across this and thought of sharing it

I saw this Salesforce community forum and got idea from there. The solution is for formula field.
I have used that in Apex using math methods and date methods

Formula: MOD(FLOOR( (Date__c -DATEVALUE("2006-01-01" ))/7),52)+1

I had to calculate number of week from the start date of year.
For the substraction part we cannot directly substract two dates so need to prepare instance of two dates and use daysbetween to find the difference.

Date todaydate = date.today();
Date todaydateinstance = date.newinstance(todaydate.year(), todaydate.month(), todaydate.day());

Integer currentyear = todaydate.year();

Date startDate = date.newinstance(currentyear, 01, 01);

integer numberDaysDue = startDate.daysBetween(todaydateinstance);

so by using this formula we can calulate in Apex

Integer numberOfWeek = math.MOD(math.FLOOR( ( numberDaysDue )/7),52)+1;

No comments: