function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Prem ChauhanPrem Chauhan 

URGENT: How to calculate the difference between first and second task created dateTime, against single lead in salesforce?

Hello SFDC Experts!

Please guide me that, how to calculate the difference between first and second task created Date &Time and against the single lead salesforce  

I have created 1 field in Lead Object Named as "Lead Difference DateTime" and I want to update this field by calculating the difference between first and second task created Date &Time against that taged lead. 

Thanks in Advance. 
 trigger TaskTrigger on Task (after insert) {
    if(Trigger.isAfter) {
        if(Trigger.isInsert) {

public class TaskTriggerHandler {
    public static void onAfterInsert(List<Task> tasks) {
        // Set to Store the Lead Id from Task
        Set<Id> taskLeadIds = new Set<Id>();
        // Loop to iterate over the Task
        for(Task task : tasks) {
        List<Task> taskList     = getLatestTask(taskLeadIds); // Fetching the Task Records based on Desc order
        Map<Id, Lead> leadMap     = getLeads(taskLeadIds); // Fetching the related Lead record
        // To calculate the difference we need 2 task records so the size should be greater than 2
        if(taskList.size() > 2) {
            // Loop to iterate over the Task List
            for(Task task : taskList) {
                // Condition to check for the lead record
                if(leadMap.containsKey(task.WhoId)) {
                    Integer days = taskList[1].CreatedDate.Date().daysBetween(taskList[0].CreatedDate.Date());
                    leadMap.get(task.WhoId).Lead_Difference_DateTime__c  = taskList[1].CreatedDate.addDays(days);
            update leadMap.Values();
        } catch(DMLException e) {
            System.debug('Unable to Update the Lead Record : ' + e.getMessage());
    // Method to get the Task Records that created for a Lead
    private static List<Task> getLatestTask(Set<Id> taskIds) {
        List<Task> taskList = [SELECT ID, WhoId, CreatedDate FROM Task where WhoId = :taskIds Order By CreatedDate Desc];
        return taskList;
    // Method to prepare the Map from Lead Ids.
    private static Map<Id, Lead> getLeads(Set<Id> taskIds) {
        Map<Id, Lead> leadMap = new Map<Id, Lead>();
        List<Lead> leads = [SELECT ID FROM Lead WHERE ID = :taskIds];
        for(Lead lead : leads) {
            leadMap.put(lead.Id, lead);
        return leadMap;