Skip to main content

Posts

Showing posts with the label apex

How to Calculate the Day of the Week from a Date and Actual Time Spent Between Two Date-Times in Apex

When working with Salesforce, there are instances where we need to compute the day of the week from a given date or determine the actual time spent between two date-time values, considering only business hours. For example, if we need to track the exact amount of time a user spent on a Lead, Case, or Task, simply subtracting two date-time values won't suffice if we need to exclude non-working hours. In this post, we will cover: How to determine the day of the week from a given date in Apex. How to calculate actual time spent between two date-times, while considering business hours (Monday to Friday: 8 AM - 8 PM, Saturday & Sunday: 8 AM - 4:30 PM). 1. How to Determine the Day of the Week from a Date in Apex Salesforce does not provide a direct method to get the day name (Monday, Tuesday, etc.) from a Date field. However, we can achieve this using toStartOfWeek() and daysBetween() methods . public static String getDayOfWeek ( Date inputDate ) {     // Get the start...

How to define generic null check of fields ?

  Use Case : Lets say you have a requirement to copy modified field values from latest opportunity to Account , then how can you do field mapping effectively ?  Assumptions: We are not using any flows here.  Step - 1 Get all Account Ids from Opportunity Trigger/trigger helper Step -2 Query Account and Its related opportunity records, assume you want to define latest opportunity by LastStageChangeDate, you can use createdDate too. This will give account details and latest opportunity without the new values that has been modified. so this is basically old opportunity.  private static List < Account > getAccounts ( set < id > accountIdset ){     return [ SELECT id , Field_1__c , Field_2__c , Field_3__c , Field_4__c , PersonEmail , Phone ,                                             ( SELECT id , Field_1__c , Field_2__c , Field_3__c , ...

How to split String from the character '*' ?

 This is a bug in split function, it does not work for '*'  or '+'.  We will get runtime error. System.StringException: Invalid regex: Dangling meta character '*' near index 0 *  String sBody = '*   Building Name:Brookwood Gardens  *   Is your unit isolated with barrier systems in place?Yes  *   Does your unit have its own supplies?Yes  *   Does your unit have any additional infection control equipment?HVAC filters: YesUVC lights: Yes'; List<String> strList = sBody.split('*'); // This will throw error. system.debug('strList '+strList); Solutions:  List<String> strList =sBody.split('\\*');  // This will solve.