1

I have an object X__c which has 2 date fields D1__c & D2__c. There are meny records for this object X__c. I want to get from all records the earliest date value from D1__c field and latest date value from D2__c field. How can I achieve this in apex class and display in another date field?

1

2 Answers 2

4

As @KeithC mentioned, you can use aggregates for this:

public class DateCombination
{
    public final Date minD1;
    public final Date maxD2;
    public DateCombination(Date min, Date max)
    {
        this.minD1 = min;
        this.maxD2 = max;
    }
}
public static DateCombination getDateRange()
{
    AggregateResult all = [SELECT MIN(D1__c) minD1, MAX(D2__c) maxD2 FROM X__c];
    return new DateCombination((Date)all.get('minD1'), (Date)all.get('maxD2'));
}
4
  • Great that you have used a class to process this instead of just using an aggregate SOQL. Can we use a static method on a parameterized constructor ?
    – Jarvis
    Commented Feb 8, 2016 at 19:58
  • @Bennie Not sure I understand your question. Can you rephrase?
    – Adrian Larson
    Commented Feb 8, 2016 at 20:00
  • Can we write/compile a class with a parameterized constructor and without a default constructor(non-parameterized) ?
    – Jarvis
    Commented Feb 8, 2016 at 20:09
  • 2
    @Bennie Sure it will compile. It is valid. You just can no longer call the empty constructor. But the DateCombination would be meaningless in such a case anyway.
    – Adrian Larson
    Commented Feb 8, 2016 at 20:10
0

If you have a SOQL query retrieving records from the X__c table, then you can use the order by clause to sort your result set by the date fields. Try something like this:

Select Id From X__c Order By D1__c desc

You'll get a pretty clean and ordered list that you can grab the first and last record from, which would be the earliest/latest D1__c value.

Another alternative, if you somehow obtain a List through means other than a SOQL query (i.e. a trigger), is that you can use the sort() method: https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_list_sorting_sobject.htm

Check out that doc for a pretty good explanation on how you can create your own wrappers that implement the Comparable interface for custom sorting.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .