Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
ShowAll Questionssorted byDate Posted
ToddKruse

# better way to grab the day of the week (monday, etc) from a Date besides using a DateTime

I have the following piece of code in an apex class:

// Convert the Date object to a DateTime object

DateTime checkDate = Datetime.newInstance(compDate.year(), compDate.month(), compDate.day(), 0,0,0);

// Assign the day (monday, tuesday, etc) to a string

String dayOfWeek = checkDate.format('EEEE');

I am noticing that when I do a large number of calls to this, I am hitting the heap limit of 200,000.

All I am looking to do is check the day (monday, tuesday, etc) of a date.  But for some reason, I have to convert it to a DateTime to do this.  Is there a better way?

Thanks

--Todd Kruse

Anand@SAAS

Use combination of "ToStartofWeek()" and "day()". For e.g.

Date today = System.today();Date startOfWeek = today.toStartOfWeek();Integer dayOfWeek = today.day()-startOfWeek.day();//This should give you a value between 0 and 6 that should be able to help you determine what the day of the week is.

Anand@SAAS

Use combination of "ToStartofWeek()" and "day()". For e.g.

Date today = System.today();Date startOfWeek = today.toStartOfWeek();Integer dayOfWeek = today.day()-startOfWeek.day();//This should give you a value between 0 and 6 that should be able to help you determine what the day of the week is.

This was selected as the best answer
ToddKruse

Perfect, that did it.  Thanks for the help!

--Todd Kruse

spiker

Anand@SAAS wrote:

Use combination of "ToStartofWeek()" and "day()". For e.g.

Date today = System.today();Date startOfWeek = today.toStartOfWeek();Integer dayOfWeek = today.day()-startOfWeek.day();//This should give you a value between 0 and 6 that should be able to help you determine what the day of the week is.

Close but no cigar...the method above doesn't work when crossing month boundaries (i.e. start of week = 2010-05-30 my date = 2010-06-02). Running this code on the above example gives the result -28.

A better way to achieve this is to use Date.daysBetween as follows

```Date weekStart = theDate.toStartofWeek();
Integer dayOfWeek = weekStart.daysBetween(theDate);```

This will always give the correct result, regardless of month boundaries. It's important to note however that the order of the dates are important. If switched the result will be negative.