Skip to main content
8 of 11
Formatted & cleaned up Apex
Moonpie
  • 2.7k
  • 6
  • 15
  • 29

Difference between month calculator in salesforce formula field

I have two dates

  1. startdate : 12/26/2022
  2. enddate : 02-28-2023

if the start date is 1-15th day then the result should be the current month ex: mm-dd-yyyy[12-11-2022] Then December 1st

if the start date is 16th-31st day then the result should be the current month EX: mm-dd-yyyy[12-22-2022] Then January 1st.

if the EndDate is 1-15th day then the result should be the current month+1 EX: mm-dd-yyyy[02-11-2022] Then January 31st

if the EndDate is 16-31sh day then the result should be the current month+1 EX: mm-dd-yyyy[02-20-2022] Then Feb 28th

input start date result: December 1st

input end date result: Feb 28th

I am looking for difference in the months from startdate and enddate as per given if conditions

  1. startdate : 12/26/2022
  2. enddate : 02-28-2023 Expected Output/result : [2]

Can we do this in the formula field? I am able to do it in apex it worked but I was unable to do it in the formula field any help would be appreciated.

Formula field i tried:

IF(DAY(EndDate__c)  <= 15,(MONTH(EndDate__c)),IF(DAY(EndDate__c)  >= 16,(MONTH(EndDate__c)+1),NULL )) -
IF(DAY(StartDate__c)  <= 15,(MONTH(StartDate__c)),IF(DAY(StartDate__c)  >= 16,(MONTH(StartDate__c)+1),NULL ))

Here is the APEX code version to be more clear

Date Firstdayofleave;
Date ReturnToWork;
Date FirstDayOfLeaves=Date.newinstance(2022,12,26);
Date ReturnTWorks=Date.newinstance(2023,02,28);
if(FirstDayOfLeaves.day() <=15 && FirstDayOfLeaves.day() >=1){
    Firstdayofleave=FirstDayOfLeaves;
    System.debug('if block'+Firstdayofleave);
}else{
    if(FirstDayOfLeaves.day() >=16 && FirstDayOfLeaves.day() <=31){
        Firstdayofleave =FirstDayOfLeaves.addMonths( 1 );
        System.debug('else block'+Firstdayofleave);
    }
}
if(ReturnTWorks.day() <=15 && ReturnTWorks.day() >=1){
    ReturnToWork =ReturnTWorks.addMonths( 1 );
    System.debug('if block'+ReturnToWork);
}else{
    if(ReturnTWorks.day() >=16 && ReturnTWorks.day() <=31){
        ReturnToWork =ReturnTWorks;
        System.debug('else block'+ReturnToWork);
    }
}
Integer monthDiff = Firstdayofleave.monthsBetween(ReturnToWork);
if (ReturnToWork.day() > Firstdayofleave.day()) monthDiff++;
    System.debug(monthDiff);
Sri
  • 21
  • 4