19

I know that you get today's date like this: Date.today(). What would be the best solution to get yesterday's date?

3 Answers 3

35

Just use addDays with a negative value:

Date.today().addDays(-1)
18

You can use the addDays() functions as already mentioned, but SOQL has a Date Literal Already set up for this, and might be a bit more simple. You just simply have to query for a date of YESTERDAY

An example

list<Account> accounts = [Select Id From Account Where CreatedDate = YESTERDAY];

Here is the documentation for Date Literals. Although the addDays() works, this seems a bit more clean in some use cases.

http://www.salesforce.com/us/developer/docs/officetoolkit/Content/sforce_api_calls_soql_select_dateformats.htm

4
  • Isn't this a bad solution? YESTERDAY returns yesterdays date beginning from 12am. You are missing out on all records between 0am and 11:59am. Or did I misunderstand something? May 4, 2015 at 10:06
  • Well, if that were teh case then addDays() would be bad as well because they both return yesterday beginning from 12am. 12am is 0000, or 0am as you call it, so there is no issue with missing records created at certain times. calculatehours.com/Military_Time_Conversion_Chart.html. salesforce.com/us/developer/docs/officetoolkit/Content/… May 4, 2015 at 10:46
  • Ah yeah. Then your solution will work. If you use date.now() then you will need the addDays() function. addDays() doesn't return the date from 12am. The "today()" function is the day at 12am. If you use date.now() with addDays() then you will have the correct times. May 4, 2015 at 11:37
  • 1
    Be careful when using YESTERDAY and such. We had a code where YESTERDAY was used in execute() method of a Schedulable class and YESTERDAY was relative to the date it was submitted, not when it was run!!
    – Kacper A
    Apr 2, 2021 at 10:03
2

This also works

System.today() - 1

You must log in to answer this question.

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