Utiity method to get week number of month by passing a Datetime value

Hi Techies,

Here below is the Method that you can use in order to fetch week number in a month:

for ex:

Pass                ->     Result
..........................................
1July2016                 1
8July2016                 2
22July2016               4

and so on....

Method:
 
  public Integer weekOfMonth( Datetime dateVar){
                Date currentDate = dateVar.Date();
                Integer weekCount = 0;
                Integer startWeekResidue = 0;
                Integer endWeekResidue = 0;
                //Calculating startWeekResidue
                Date dt = currentDate.toStartOfMonth().addDays(-1);
                Date dtFirstWeekend = dt.toStartOfWeek().addDays(6);
                startWeekResidue = dt.daysBetween(dtFirstWeekend);
                //Calculating endWeekResidue
                Date dtLastWeekend = currentDate.toStartOfWeek().addDays(-1);
                endWeekResidue = dtLastWeekend.daysBetween(currentDate);
                //Counting the weeks
                weekCount = (currentDate.day() - (startWeekResidue + endWeekResidue))/7;
                weekCount += (startWeekResidue > 0 ? 1:0)+(endWeekResidue > 0 ? 1:0);
                System.debug(weekCount);
                return weekCount;
  }

Comments

Popular posts from this blog

List of Key Prefixes in Salesforce

SFDX Install CPQ in Scratch org