0

I have below code

Time startTime = objAvailableTime.StartTime;
                Time endTime = objAvailableTime.EndTime;
                List<Time> lstTime = new List<Time>();
                while(startTime < endTime){
                    lstTime.add(startTime);
                    startTime = startTime.addHours(apptDuration);
                    System.debug('start time and end time is'+startTime + ' '+endTime);
                }

The issue here I am facing is if my endTime is at 11pm at night and my startTime is at 6pm and apptDuration is 2 hours then it always remains in the loop and errors out. This is happening because at 12am time becomes 00:00 and it continues in the loop. Is there an efficient way to compare two times and increment till the end?

  • 3
    You have to use datetime field because it is not the same compare 2017-11-20T20:00:00 with 2017-11-21T00:00:00. In this case 00:00:00 is greater that 20:00:00 – Torsen Nov 20 '17 at 15:08
  • I cannot use DateTime Field. – user5129806 Nov 20 '17 at 15:29
  • it would be important to mention that in the post – glls Nov 20 '17 at 15:48
3

You can use the Datetime type here despite your comments to the contrary. If you need a List<Time>, you can call time() on each instance (similar to date(), year(), etc.).

Datetime pointer, max;
pointer = Datetime.newInstance(Date.today(), objAvailableTime.StartTime);
max = (objAvailableTime.EndTime < objAvailableTime.StartTime) ?
    Date.newInstance(Date.today().addDays(1), objAvailableTime.EndTime) :
    Date.newInstance(Date.today(), objAvailableTime.EndTime);

List<Time> times = new List<Time>();
while (pointer < max)
{
    times.add(pointer.time());
    pointer = pointer.addHours(apptDuration);
}

If you are certain that the EndTime is strictly greater than StartTime, you can just use today as the Date component of both newInstance calls:

Datetime pointer = Datetime.newInstance(Date.today(), objAvailableTime.StartTime);
Datetime max = Date.newInstance(Date.today(), objAvailableTime.EndTime);
  • My start time is 8:00 am and end time is 11pm with 2 hour duration in that case at 10pm when i add 2 hours it becomes 00:00 and it is still less than 11pm and loop continues. – user5129806 Nov 20 '17 at 16:36
  • 1
    That's why you use Datetime values...midnight tomorrow is greater than 11PM today. – Adrian Larson Nov 20 '17 at 16:44

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.