# How to count an average date?

My accounts have the Date field Activity__c. How can I figure out an average date between all these Activity__c fields and define the closest date to the average date?

I tried to use SOQL: [SELECT AVG(Activity__c) FROM Account WHERE Activity__c != null]

But it shows an error: field Activity__c does not support aggregate operator AVG.

Now I know that aggregate function average doesn't work with Date. Could somebody help me, please?

• You can make a formula, which is equal to duration between certain date and Activity__c date in days. Then you can count average of that formula, and calculate which day it is Jan 23, 2021 at 21:24
• thank you, I did it ) Jan 23, 2021 at 23:36

I did it:

//method finds closest date to average date

``````private static Date findClosestDateToAvg(){
List<Date> dates = new List<Date>();
for (Account acc : [SELECT Activity__c
FROM Account
WHERE Activity__c != NULL]) {
}

Date avgDate = calcAvgDate();
Date closestDate = findMinDate();
for (Date d : dates) {
if (Math.abs(d.daysBetween(avgDate)) < Math.abs(closestDate.daysBetween(avgDate))) {
closestDate = d;
}
}
return closestDate;
}
``````

// method calculates average date in fileds Activity__c of Account

``````private static Date calcAvgDate() {
Date minDate = findMinDate();
Date maxDate = findMaxDate();
Integer diff = minDate.daysBetween(maxDate);