[SalesForce] Get the difference between NOW() and a date Time field in seconds

I have a custom field (custom_field__c) on lead object and in my trigger i want to check difference between NOW() and current value of custom_field__c. And if difference is more than 5 seconds then do some action.

So for this requirement will below formula work 100% ? or are there any limitations or problems in it. Thanks for help:)

( NOW() - custom_field__c )*24*60*60

Also how to check if dateTime field is empty:
Will custom_field__c == Null works?

Best Answer

You need to convert the datetime to Long to calculate time difference. Refer DateTime.getTime() method

Like CurrentTime DateTime.now().getTime() will return 1490556040011L

As per your requirement the logic should be like this:

if(Custom_Field__c !=null)
{
    Long customFieldLong = Custom_Field__c.getTime() ;
    Long currentDTLong = DateTime.now().getTime();
    Long milliseconds = currentDTLong - customFieldLong;
    Long seconds = milliseconds / 1000;
    if(seconds>5)
    //perform the desired action
}
Related Topic