How Can I Tell the Day of the Week of a Date?

Formulas

There isn't a built-in function to do this for you, but you... UPDATE: As of Spring 2018, there's a built-in function for this: WEEKDAY(). It returns an integer where 1 is Sunday, 2 is Monday, 3 is Tuesday, etc.

Apex Code

You could do the same thing with time deltas, but you can also use the poorly documented DateTime.format() function:

// Cast the Date variable into a DateTime
DateTime myDateTime = (DateTime) myDate;
String dayOfWeek = myDateTime.format('E');
// dayOfWeek is Sun, Mon, Tue, etc.

Another alternative that avoids the pitfalls of format() returning locale specific values is to use the daysBetween() function between a known date and the comparison. (This is the apex equivalent to your formula)

For example the 1st Jan 1900 is a Monday, so the following code will give you the day of the week index with Monday being 0.

Math.mod(monday.daysBetween(dateValue), 7)

It is important to note that this will only work for days greater than the fixed date, the below assertions show this (the last assertion fails)

Date monday = Date.newInstance(1900, 1, 1);

Date wednesday = Date.newInstance(2012, 11, 14);
Date thursday = Date.newInstance(1900, 1, 4);
Date sunday7 = Date.newInstance(1900, 1, 7);

System.assertEquals(2, Math.mod(monday.daysBetween(wednesday), 7));
System.assertEquals(3, Math.mod(monday.daysBetween(thursday), 7));
System.assertEquals(6, Math.mod(monday.daysBetween(sunday7), 7));

//Date before the fixed monday, result is -3
System.assertEquals(4, Math.mod(sunday.daysBetween(Date.newInstance(1899, 12, 28)), 7));

Since Apex uses Java's SimpleDateFormat, you can get the full name of the day of the week.

Date d = System.today();
Datetime dt = (DateTime)d;
String dayOfWeek = dt.format('EEEE'); //This returns - Monday, Tuesday, Wednesday, etc..

Basically the same apex code as @Benj provided except the format part. For a full list of supported formats, check [SimpleDateFormat Class][1]

Be careful when using format method as it converts to the local time zone of the context user, consider using formatGmt or format(dateFormat, timezone) if dealing with different timezones. For more information on this check [Apex Datetime Methods][2]

[1]: http://docs.oracle.com/javase/6/docs/api/java/text/SimpleDateFormat.html [2]: http://www.salesforce.com/us/developer/docs/apexcode/Content/apex_methods_system_datetime.htm