mardi 15 août 2017

How to calculate monthly occurrence in java

I need to be able manage dates in flexible way for calculating monthly events.

If I use

    SimpleDateFormat sdf = new SimpleDateFormat("dd-M-yyyy hh:mm:ss");

    Calendar calendar = Calendar.getInstance();
    calendar.set(2017, Calendar.AUGUST, 31, 9, 30, 15);
    Calendar next = calendar;
    for (int i = 1; i++<10;) {
        next = (Calendar) calendar.clone();
        next.add(Calendar.MONTH, i);
        System.out.println(sdf.format(next.getTime()));
    }

in result you can see

31-10-2017 09:30:15

30-11-2017 09:30:15

31-12-2017 09:30:15

31-1-2018 09:30:15

28-2-2018 09:30:15

31-3-2018 09:30:15

30-4-2018 09:30:15

31-5-2018 09:30:15

30-6-2018 09:30:15

It seems following month semantic if we add one moth to date we should get next month (it's correct), but following occurrence semantic it has an issue, because of acceptance is to get same date day but in next month (as you can see it is not same sometimes. There are 31, 30, 28). If there is no same date, we should null for example.

Does java provides ability calculate months following occurrence semantic strategy to handle my issue?

Aucun commentaire:

Enregistrer un commentaire