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
Sujit KarandeSujit Karande 

How to get the difference between DateTime fields in Apex trigger?

Hi,

I have two DateTime fields ApprovedAt, SubmittedAt.

What I am trying to do is I would like to calculate turn around time by using this -> (ApprovedAt - SubmittedAt)

How we can do that in APex trigger? And what should be the type of field TurnAroundTime

I appreciated your help.
Best Answer chosen by Sujit Karande
SandhyaSandhya (Salesforce Developers) 
Hi,

Date startDate = Date.newInstance(2008, 1, 1); Date dueDate = Date.newInstance(2008, 1, 30); Integer numberDaysDue = startDate.daysBetween(dueDate);

Also refer below link.

http://sfdcsrini.blogspot.com/2014/08/different-date-time-calculation-steps.html
 
Please mark it as solved if my reply was helpful. It will make it available for other as the proper solution.
 
Best Regards
Sandhya
 

All Answers

SandhyaSandhya (Salesforce Developers) 
Hi,

Date startDate = Date.newInstance(2008, 1, 1); Date dueDate = Date.newInstance(2008, 1, 30); Integer numberDaysDue = startDate.daysBetween(dueDate);

Also refer below link.

http://sfdcsrini.blogspot.com/2014/08/different-date-time-calculation-steps.html
 
Please mark it as solved if my reply was helpful. It will make it available for other as the proper solution.
 
Best Regards
Sandhya
 
This was selected as the best answer
Keyur  ModiKeyur Modi

Hi Sujit,

you can refer below code which will help you to find difference in Days,Hours,Minutes,Second. 

Long dt1Long = DateTime.now().addDays(-1).getTime();
Long dt2Long = DateTime.now().getTime();
Long milliseconds = dt2Long - dt1Long;
Long seconds = milliseconds / 1000;
Long minutes = seconds / 60;
Long hours = minutes / 60;
Long days = hours / 24;

If you want to show DD HH:MM:SS then you can create string field and you can capture in particlar formate with help of typecasting values in string and merge those strings in one field(TEXT).

If you want store number of days in Number field type then try below code it will help.
 
Long dt1Long = DateTime.now().addDays(-1).getTime();
Long dt2Long = DateTime.now().getTime();
Long milliseconds = dt2Long - dt1Long;
Long seconds = milliseconds / 1000;
Long minutes = seconds / 60;
Long hours = minutes / 60;
Long days = hours / 24;

Account acc = new Account();
acc.Name= 'Test123';
acc.NumberOfEmployees = Integer.ValueOf(days); // here storing  days in number field so type caste it to Integer, if you are capturing minutes then you can type cast it to decimal.
insert acc;


Please try and let me konw if I can help further.

Thanks,
Keyur Modi

Sujit KarandeSujit Karande
@Sandhya - Much Much Much Appreciated, It works like a charm. You saved my job :)  (The solution given in your links worked)


@Keyur - Appreciated you time and help