Search code examples
salesforceapexsoql

SOQL date in week where clause


I have a custom object with a Date field and I was wondering how you could query that object if that date field is within the current week (given that the week starts on Sunday and ends on Saturday). I was thinking of creating two functions that find the specific date for the first day of the week and last day of the week and just doing:

SELECT Id, MyObjectDate FROM MyObject WHERE MyObjectDate > getWeekStartDate(todaysDate) AND MyObjectDate < getWeekEndDate(todaysDate)

But I feel like there is an easier way. Any tips would be appreciated!


Solution

  • Use toStartOfWeek method to get Start date of week.Check this.

    The toStartOfWeek method returns the start of the week for the Date that called the method, depending on the context user's locale. For example, the start of a week is Sunday in the United States locale, and Monday in European locales.

      public Date WeekFrom {get; set;}
      public Date WeekTo {get; set;}
      .....
      WeekFrom = todaysDate.toStartofWeek();
      WeekTo = WeekFrom.adddays(6);
    
      SELECT Id, MyObjectDate FROM MyObject WHERE MyObjectDate > WeekFrom  AND MyObjectDate < WeekTo
    

    Hope it helps you