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

  • 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?

  • Benj

    Benj Correct answer

    9 years ago

    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.
    

    ditto @MikeChale, +1 for Datetime.format()

    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.

    +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.

    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).

    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: http://salesforce.stackexchange.com/questions/117163/datetime-day-returning-inconsistent-value#117163

    Please note that casting a `Date` to a `Datetime` may introduce off-by-one errors due to time zone issues.

License under CC-BY-SA with attribution


Content dated before 7/24/2021 11:53 AM