2

I'm trying to break a range of dates into equal intervals. Here is the code that I'm using. (Dates are in YYYY-MM-dd format)

    Integer frequency= 4;
    Date startDate = '2020-02-27';
    Date endDate = '2022-02-26';
    String[] startD = string.valueOf(behadelPlan.Start_datum__c).split('-');
    String[] endD = string.valueOf(behadelPlan.Einddatum__c).split('-');

    //String[] dates;
    Integer x = 0;
    Integer startYear = Integer.valueof(startD[0]);
    Integer endYear = Integer.valueof(endD[0]);
    //while (x < 4) {
    for (Integer i = startYear; i <= endYear; i++) {
        Integer endMonth = i != endYear ? 11 : Integer.valueof(endD[1]) - 1;
        Integer startMon = i == startYear ? Integer.valueof(startD[1]) - 1 : 0;
        for (Integer j = startMon; j <= endMonth  && x < frequency; j = j + 1) {
            Integer month = j + 1;
            String displayMonth;
            if (month < 10) {
                displayMonth = '0' + month;
            } else {
                displayMonth = String.valueOf(month);
            }
            List<string> slist = new string[]{string.valueOf(i), displayMonth, '01'};
                string allstring = string.join(sList,'-');
           System.debug(slist);
            x+=1;
        }

    }

when I run this I get the output as

2020-02-01
2020-03-01
2020-04-01
2020-05-01

Here In my case, I want to generate the dates at equal(monthly with the day being start dates day) intervals. In the above example, I should be getting the resultant dates as 4 equal intervals (as I've given my frequency in a number of months).

Please let me know on how can I achieve this.

Here is a simple example.

startdate = '2020-01-01'
endDate = '2020-12-01'
frequency = 4

output should be

2020-01-01
2020-03-01
2020-06-01
2020-09-01
Angshu31
  • 1,172
  • 1
  • 8
  • 19
user3872094
  • 3,269
  • 8
  • 33
  • 71
  • Why'd you tag it JS? – Angshu31 Feb 21 '20 at 08:23
  • Is not very clear for me what you wish to achieve. Do you want transformation yearly quarterly. What happen if startDate = 2018-04-06 and endDate = 2020-10-06. – Magdalena Fairfax Feb 21 '20 at 08:33
  • Sounds not very complicated. Compute first how many months between start and end date, then divide by frequency and then add the result frequency-times to the start-date. – Ralf Renz Feb 21 '20 at 08:37
  • @MagdalenaFairfax, We have a start date and end date. And another number name frequency. I basically want to extract the dates between the start and end date (including start date) based on the frequency (in months) and print them. As per your example, I need to divide the dates between start and end dates into 4 equal intervals and print the dates. – user3872094 Feb 21 '20 at 08:41
  • @user3872094 I have posted an possible answer let me know if that works – Amit Kumar Lal Feb 21 '20 at 09:06
  • _when I run this_ How do you run it? It doesn't even compile for me. Is it java code? – Abra Feb 21 '20 at 09:17
  • @user3872094 if it works for you , you can accept the answer also. – Amit Kumar Lal Feb 21 '20 at 10:29

2 Answers2

2

Here is how I would do it. I will us class Calendar for this.

public class FrequencyTransform {

public static void main (String[] args) {
    System.out.println("Split a date into equal intervals based on a given frequency");
    Integer frequency= 4;
    try {
        Date startDate = new SimpleDateFormat("yyyy-mm-dd").parse("2020-02-27");
        Date endDate = new SimpleDateFormat("yyyy-mm-dd").parse("2021-02-26");

        Calendar startCalendar = Calendar.getInstance();
        startCalendar.clear();
        startCalendar.setTime(startDate);

        Calendar endCalendar = Calendar.getInstance();
        endCalendar.clear();
        endCalendar.setTime(endDate);

        // id you want the interval to be months
        int monthsElapsed = elapsed(startCalendar, endCalendar, Calendar.MONTH);
        System.out.println("Number of months between dates:" + monthsElapsed);
        int interval = monthsElapsed % frequency;
        System.out.println("For the frequency 4 the interval is: " + interval);

        while (!startCalendar.after(endCalendar)){
            startCalendar.add(Calendar.MONTH,interval);
            Date auxDate= startCalendar.getTime();
            System.out.println(auxDate);
        }
    }
    catch (ParseException ex) {
        ex.printStackTrace();

    }


}

private static int elapsed(Calendar before, Calendar after, int field) {

    Calendar clone = (Calendar) before.clone(); // Otherwise changes are been reflected.
    int elapsed = -1;
    while (!clone.after(after)) {
        clone.add(field, 1);
        elapsed++;
    }
    return elapsed;
}

}

This is just a quick example. You can take it from here. The thing is Calendar allow you to use different time units. Instead of Calendar.MONTH you can use Calendar.DATE for days, Calendar.YEAR for year. Wasn't very sure how you wanted to do the split.

1

Sample code ,

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class SOTest {

    static DateFormat dateFormat = new SimpleDateFormat("yyy-MM-dd");

    public static void main(String[] args) {
        try {
            String startDateString = "2020-01-01";
            String endDateString = "2020-12-01";

            int frequency = 4;
            Date startDate = (Date)dateFormat.parse(startDateString);
            Date endDate = (Date)dateFormat.parse(endDateString);
            Long intervalSize = (endDate.getTime()-startDate.getTime())/frequency;

            for(int i=0; i<= frequency && intervalSize > 0; i++) {
                Date date = new Date(startDate.getTime()+intervalSize*i);
                System.out.println("Date :: "+dateFormat.format(date));
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }   
    }
}

output for above ::

Date :: 2020-01-01
Date :: 2020-03-24
Date :: 2020-06-16
Date :: 2020-09-08
Date :: 2020-12-01

For input :: startDate = '2020-02-27' , endDate = '2022-02-26', interval = 4

Date :: 2020-02-27
Date :: 2020-08-27
Date :: 2021-02-26
Date :: 2021-08-27
Date :: 2022-02-26
Amit Kumar Lal
  • 5,537
  • 3
  • 19
  • 37