-4

I have a list of Date objects, and a target Date. I want to find the date in the list that's nearest to the target date, but only dates that are after the target date.

Example: 2008-10-1 2008-10-2 2008-10-4

With a target date of 2008-10-3, I want to get 2008-10-4

What is the best way to do it?

3
  • TargetDate is separate field or you can store all date in single fields ? Commented Apr 29, 2015 at 9:38
  • 3
    What did you try so far? Pls include a code example. Commented Apr 29, 2015 at 9:49
  • Based on your tag, you're trying to do this in AMPScript in the SF Marketing Cloud, correct? Commented Apr 29, 2015 at 14:00

2 Answers 2

1

Sort the list of dates, read through it and then stop as soon as you get to a date that is >= the one you want.

list<Date> dates = new list<Date>();

//add all the dates;

dates.sort();

//now the list is ordered from oldest date to newest
2
  • I believe he's looking for an AMPScript solution. Commented Apr 29, 2015 at 14:03
  • doh! I need to read more carefully next time...
    – Dominic
    Commented Apr 29, 2015 at 14:18
-1

Dominic's answer is the smartest way. Here is another way

List<Date> dateList = new List<Date>();

dateList.add(Date.Today()+1);
dateList.add(Date.Today()-2);
dateList.add(Date.Today()-1);

Date target = Date.today();
Integer days = 100000000;
Date nearest = target;
Integer count = 0;
do{
    Date d = dateList.get(count);
    if(d>target && days>target.daysBetween(d))
    {

            days = target.daysBetween(d);
            nearest = d;
    }
    count++;
}while(count < dateList.size());
System.debug('nearest'+nearest.day());
4
  • Ampscript has sort function? Commented Apr 29, 2015 at 10:19
  • Where did I use sort function? Commented Apr 29, 2015 at 11:05
  • There isn't a sort function in AMPScript. Commented Apr 29, 2015 at 14:01
  • Oh! I didn't notice it! I don't have much expertise in AMPScript. Commented Apr 29, 2015 at 15:07

You must log in to answer this question.

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