54

I'd like to build in some logic based on the weekday (e.g. Monday, Tuesday, Wednesday) of a given date. How can I identify the date, using either formulas or Apex code?

8 Answers 8

73

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.
6
  • ditto @MikeChale, +1 for Datetime.format() Sep 6, 2012 at 13:38
  • 1
    Re: Apex Code method: Will that always use the English abbreviations (Mon, Tue, Wed, etc.), or is it localized? If localized, you wouldn't want to try converting the String to a number, or assume that a date is a weekend if it's "Sat" or "Sun". In that case, an Apex version of the formula is a safer method.
    – tomlogic
    Sep 10, 2012 at 23:33
  • 1
    +1 from me too, you have no idea how many times I had to tell my colleagues that Date.toStartOfWeek() gives Sunday for all these weird users with en_US locale ;) @tomlogic - yes, guaranteed to be always English.
    – eyescream
    Nov 15, 2012 at 23:07
  • 10
    I know this is an old thread, but myDateTime.format('u') may be a better option -- it returns "Day number of week (1 = Monday, ..., 7 = Sunday)". According to the documentation. format() uses the locale of the current user, so I wouldn't want to bank on .format() always returning english words for days (if it does now, that may be "fixed" in the future).
    – jkraybill
    Jun 12, 2015 at 2:50
  • 3
    One word of caution re casting the date to a datetime - you can end up on the wrong day and begin to question your sanity...you are better off doing a new instance and setting the time - see here for more details: salesforce.stackexchange.com/questions/117163/… Apr 7, 2016 at 22:58
26

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));
4
  • Great solution to the this! Going to be handy knowing 1st Jan 1900 is a Monday!
    – Matt Lacey
    Oct 7, 2013 at 6:36
  • This is great! Since Apex has Date and DateTime as different type. Would this be true for all timezones that 1st Jan 1990 is Monday?
    – devilpreet
    Jan 9, 2019 at 12:38
  • 1
    @devilpreet Yes, since there is no time component, 1st Jan 1900 in Hawaii is just like 1st Jan 1900 in Australia. Apr 28, 2020 at 22:11
  • Hello. The code is great. The monday should be changed to known sunday = Date.newInstance(1900, 1, 7); - as from salesforce docs blog.bessereau.eu/assets/pdfs/formula_date_time_tipsheet.pdf Aug 2, 2021 at 12:45
16

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

2
  • 1
    Your SimpleDateFormat link is a 404 Apr 8, 2016 at 0:31
  • This can provide misleading results in some cases. Getting the date (without the time) and then converting to a datetime puts into GMT time. Depending on your location and the time of day you run this, you can actually get the wrong day of the week. Better to get the DateTime directly using System.now() and use that to get day of the week. Aug 1 at 0:19
8

For SOQL queries, you can use the DAY_IN_WEEK() Date Function.

7

For reference, an Apex code version of the modular division approach is:

public static Integer dayOfWeekNumber(Date aDate) {
    return Math.mod(Date.newInstance(1900, 1, 7).daysBetween(aDate),7);
}

Sun = 0, Sat = 6

1
3

I know all the answers are correct and enough, but I wanted to know this is also the way you can calculate the day of week. Day number of week (1 = Monday, ..., 7 = Sunday) for Date or Time Component. Please refer this : https://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html for more info.

Date d = System.today();
Datetime dt = (DateTime)d;
String dayOfWeek = dt.format('u');
System.debug('~~~~~~~~~ ::'+dayOfWeek);
1

Other than the modular division method, the most reliable and brief solution is this:

DateTime dt = DateTime.newInstance(myDate, Time.newInstance(0,0,0,0));
String dayOfWeek = dt.format('u');

This assigns the numeric day of the week in String form (1=Monday, 2=Tuesday, ... , 7=Sunday) to dayOfWeek. If you simply cast to DateTime, the time zone adjustment will reach out and bite you.

0

Simplified everything for myself from the examples below, maybe you will come in handy :)

public static Integer getWeekdayNumberFromDate(Date fromDate) {
    return Integer.valueOf(((Datetime) fromDate).format('u'));
}

You must log in to answer this question.

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