24

I would like to ask about the definition of LAST_N_DAYS:n

For the number n provided, starts 00:00:00 of the current day and continues for the past n days.

Is

CreatedDate = LAST_N_DAYS:1

equal to

(CreatedDate >= 2017-08-30T00:00:00Z AND CreatedDate <= 2017-08-30T23:59:59Z)
OR CreatedDate  = TODAY

and

CreatedDate >= YESTERDAY

To be more specific, isn't LAST_N_DAYS in fact LAST_N_DAYS + 1 (Today)?

2
  • 3
    Nice first question! Looks like the documentation is in fact wrong.
    – Adrian Larson
    Aug 31, 2017 at 18:24
  • I'm not sure about salesforce, but in other languages it's common to cast/truncate the time portion away to get just a date, which in this case means that the range starts at 2017-08-31 00:00:00 (which becomes 2017-08-31) and continues for the past 1 days, ending at 2017-08-30 00:00:00 (which is 2017-08-30 when cast to a date). If it works that way, then starting today (at midnight) and going back 1 day, does in fact give you 2 days worth of time (though I wouldn't consider the documentation wrong... more ambiguous)
    – A C
    Aug 31, 2017 at 19:39

2 Answers 2

26

In contradiction to what the current documentation claims, you can observe that the LAST_N_DAYS date literal includes today's data.

To be sure, I ran this query:

SELECT CreatedDate FROM MyObject__c
WHERE CreatedDate = LAST_N_DAYS:1
ORDER BY CreatedDate DESC LIMIT 1

And I got back:

2017-08-31T18:16:17.000+0000

4
  • 2
    Hmm... the documentation says For the number n provided, starts 00:00:00 of the current day and continues for the past n days. Apparently, it lies.
    – sfdcfox
    Aug 31, 2017 at 18:20
  • 4
    Right, the documentation is incorrect here.
    – Adrian Larson
    Aug 31, 2017 at 18:20
  • The trouble with this is that Salesforce could claim that either the documentation was wrong and correct it or that the platform was not behaving correctly and change the behaviour. Relying on this to cover today is, therefore, potentially risky.
    – Phil W
    Dec 15, 2018 at 10:01
  • 1
    I certainly never contend you should rely on it including today. However, it is extremely unlikely they would change the behavior and hammer testing should prevent it anyway.
    – Adrian Larson
    Dec 15, 2018 at 17:21
2

I used the following in my WHERE clause, and it works as a replacement that operates the same as LAST_N_DAYS is documented as expecting to work.

SELECT Id
FROM MyObject__c
WHERE CreatedDate = LAST_N_DAYS:n AND CreatedDate < TODAY

Explanation: TODAY represents a range that "Starts 00:00:00 of the current day and continues for 24 hours." LAST_N_DAYS:n is supposed to represent a range that, "starts 00:00:00 of the current day and continues for the past n days," but in practice, appears to be the expected range union TODAY. Thus, by removing anything that is in the TODAY range, we have the expected range.

You must log in to answer this question.

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