I'm trying to write an Apex method to merge days with similar start and end hours together. For example, the data looks like

Hours:{Name=ConsultantHours, SundayStartTime=00:00:00.000Z, SundayEndTime=00:00:00.000Z, MondayStartTime=08:00:00.000Z, MondayEndTime=18:00:00.000Z, TuesdayStartTime=07:00:00.000Z, TuesdayEndTime=19:00:00.000Z, WednesdayStartTime=08:00:00.000Z, WednesdayEndTime=18:00:00.000Z, ThursdayStartTime=09:00:00.000Z, ThursdayEndTime=20:00:00.000Z, FridayStartTime=07:00:00.000Z, FridayEndTime=19:00:00.000Z, SaturdayStartTime=00:00:00.000Z, SaturdayEndTime=00:00:00.000Z, TimeZoneSidKey=America/Los_Angeles}

I have to use all the above data except Name and Timezone and merge days based on Start and End time. we have to simplify like

Monday & Wednesday : 8:00 a.m. to 6:00 p.m Tuesday & Friday : 7:00 a.m. to 7:00 p.m Thursday : 9:00 a.m. to 8:00 p.m Saturday & Sunday : Holiday

And, if the data is

Hours:{Id=01mS0000000CeCVIA0, Name=ConsultantHours, SundayStartTime=00:00:00.000Z, SundayEndTime=00:00:00.000Z, MondayStartTime=08:00:00.000Z, MondayEndTime=18:00:00.000Z, TuesdayStartTime=08:00:00.000Z, TuesdayEndTime=18:00:00.000Z, WednesdayStartTime=08:00:00.000Z, WednesdayEndTime=18:00:00.000Z, ThursdayStartTime=09:00:00.000Z, ThursdayEndTime=20:00:00.000Z, FridayStartTime=09:00:00.000Z, FridayEndTime=20:00:00.000Z, SaturdayStartTime=09:00:00.000Z, SaturdayEndTime=20:00:00.000Z, TimeZoneSidKey=America/Los_Angeles}

We have to simplify like

Monday- Wednesday : 8:00 a.m. to 6:00 p.m Thursday - Saturday : 9:00 a.m. to 8:00 p.m Sunday : Holiday

Is there a way of accomplishing this using Apex coding ?

The Query I used to fetch the above data is :

List hrLst = [SELECT Id, Name, SundayStartTime, SundayEndTime, MondayStartTime, MondayEndTime, TuesdayStartTime, TuesdayEndTime, WednesdayStartTime, WednesdayEndTime, ThursdayStartTime, ThursdayEndTime, FridayStartTime, FridayEndTime, SaturdayStartTime, SaturdayEndTime, TimeZoneSidKey FROM Hours WHERE Name = 'ConsultantHours' AND IsActive = TRUE];

1 Answer 1


You can use a combination of apex collection data types, a set of string to hold the days of the week, a Map of List data type to group the days by the start-end time.

Set<String> days = new Set<String>{'Monday', ..., 'Sunday'};
Map<String, List<String>> daysByTime = new Map<String, List<String>>();
// assuming hour is your Hours sobject
for (String day : days) {
   String key = hour.get(day + 'StartTime') + hour.get(day + 'EndTime');
   if (!daysByTime.containsKey(key)) {
       daysByTime.put(key, new List<String>>());
// print out by looping thru the map keys
for (String key : daysByTime.keySet()) {
   // get the first index of list using .get(0)
   // get the last index of list .get(list size()-1)

You need to perform a bit of formatting on the date to display them as what you wanted. Check out the DateTime apex class reference.

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