Home SALESFORCEAPEX Find the last day of the month from a given date using Formula field or Apex in Salesforce

Find the last day of the month from a given date using Formula field or Apex in Salesforce

Find the last day of the month from a given date using Formula field or Apex in Salesforce

by Sakthivel Madesh

Find the last day of the month from a given date using Formula field or Apex in Salesforce

Find the last day of the month from a given date using Apex in Salesforce

https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_methods_system_date.htm

Date StartDate = date.parse(’16/08/2022′);

Integer getDay = StartDate.Day(); //get day
System.debug(‘getDay::’+getDay);
Integer getMonth = StartDate.Month(); //get Month
System.debug(‘getMonth::’+getMonth);
Integer getYear = StartDate.Year(); //get Year
System.debug(‘getYear::’+getYear);

Integer numberOfDaysInMonths = Date.daysInMonth(StartDate.year(), StartDate.month());
Date lastDayOfMonth = Date.newInstance(StartDate.year(), StartDate.month(), numberOfDaysInMonths);
System.debug(‘numberOfDaysInMonths::’+numberOfDaysInMonths);
System.debug(‘lastDayOfMonth::’+lastDayOfMonth);
Integer lastDay = lastDayOfMonth.Day(); //get day value
System.debug(‘lastDay::’+lastDay);

 

Same is possible to achieve from Salesforce formula and this you can use it in your formula field creation, formula from your Salesforce flow

IF(
MONTH(StartDate__c)=12,
DATE(YEAR(StartDate__c)+1,1,1)-1,
DATE(YEAR(StartDate__c),MONTH(StartDate__c) + 1,1) -1
)

Result Return as if the StartDate__c as 16/08/2022 then its return as 31/08/2022

You may also like

Leave a Comment