Search code examples
salesforceapex-codevisualforce

find the Day of week of a particular date


i have an object which has 2 dates startdate_c and enddate_c . i need to find a way to find the days of week these dates fall in

For example startdate = 1 jun 2012 and enddate = 3 jun2012 I need to know which days of the week the days between these dates fall in. In this example Mon = false, tue = false, wed = false, thu=false, fri=true,sat=true,sun=true

I want to use this in a Vf page to render the somefields based on the boolean value.

Any pointers would be of great help.


Solution

  • Date has a method called toStartOfWeek which you could leverage, assuming your two dates do lie within the same week you could simply do something like this:

    date weekStart = startdate.toStartOfWeek();
    list<boolean> days = new list<boolean>();
    
    for(integer i = 0; i < 7; i++)
    {
      days.add(weekStart.addDays(i) >= startdate && weekStart.addDays(i) <= enddate);
    }
    

    A little bit crude, but it'll give you an array of 7 boolean values. For longer/unknown ranges you could use a date cursor and increment that instead of an integer here, but this should get you started. Note, I've not tested this code ;)