We will cover all that you need to know in order to calculate the total number of days elapsed between two given dates.
You will need the following fields:
- Created, Field Type: Date
- Close Date, Field Type: Date
This could be used to know how many days passed since an Opportunity was created until it was closed (won), or any number of similar approaches for other Apps, like Contacts, where you would consider when the Contact was created and count the number of days elapsed until it became a Customer or it reached a given Stage.
You can use the names that best suit your organization for these fields. You will just need to replace their names in the code snippet below.
If you want to learn how to create Fields, please visit the following tutorial:
Fields
Give your new field a name that will allow you to identify it and enter a description, although optional, it can be used to explain to other users that this is a Calculated field. The type should be set to 'Number' and you will need to check the 'Calculated' box in order to display the calculation section. Then copy & paste the code below:
(function(deal){
var StartDate = Date.parse(deal.Created);
var EndDate = Date.parse(deal['Close Date']);
var timeBetween = EndDate - StartDate;
var days = timeBetween / (24 * 60 * 60 * 1000);
var justDays = parseInt(days);
return justDays;
}(deal));
If your fields have different names, you would need to replace the bold parts with the right field name. To get a list of all the existing fields use 'CTRL + Space'. Once you are done, click the Save button. This calculation will occur when the information on the Created and the Close Date fields have information.
You could add validation for this calculation to return a '0' if the Close Date is not available. For that, you only need to add an 'IF' statement, as shown below (bold).
(function(deal){
var StartDate = Date.parse(deal.Created);
var EndDate = Date.parse(deal['Close Date']);
if(!EndDate){
return 0;
}
var timeBetween = EndDate - StartDate;
var days = timeBetween / (24 * 60 * 60 * 1000);
var justDays = parseInt(days);
return justDays;
}(deal));