2

I am trying to set a next schedule date for a process to run. This scheduler needs to display up a Vf page when the user logs in or when he loads up a page. I am running a scheduled batch process to populate a field for the next scheduled date. If the user chooses a monthly schedule where in it needs to run on a particular date of every month.

I am unsure of how to calculate the date for the days 29,30 and 31 as they are not there for every month of the year. If i try to create a new date instance for the months these days are not valid then it would throw an exception.

If these days are not available for the month then i need to somehow have it set it to the next valid date.

Any thoughts on how to approach this

public DateTime getmonthlyNextscheduleDate(String day, String times)
 {
    Date monthDate;
    Datetime monthDateTime;
    DateTime nextScheduleDate;
    if(day == '29' || day =='30' || day =='31')
    {

    }
    else
    {
    monthDate = Date.newInstance(Integer.valueof(day),Date.today().month(),Date.today().year());
    monthDateTime = Datetime.newInstance(monthDate, gettimes(times));
    if(monthDateTime > Datetime.now())
    {
        nextScheduleDate = monthDateTime.addMonths(1);
    }
    else
    {
        nextScheduleDate = monthDateTime;
    }
    }
    return nextScheduleDate;
 }
5

An ugly way would be just catching the exception and calling your function recursively with day - 1. A bit more elegant way would use daysInMonth function like this.

Integer daysInMonth = Date.daysInMonth(Date.today().month());
while( day > daysInMonth){
      day--;
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.