2

it's a date time field (my_date_field__c)

I have to update the record if my_date_field__c is within the past 24 hours (> yesterday at 5pm and <= today at 5pm)

I was thinking to use a logic to add 5pm hours in YESTERDAY function to make it 5 pm from TODAY function

select id,my_date_field__c from employee__c where my_date_field__c = TODAY and HOUR_IN_DAY(my_date_field__c ) = 5

but it does not seems to be working and for testing I set the my_date_field__c value to be 5/28/2021 5:00 PM

Any idea how to achieve this soql/apex?

2
  • This is a date time field, right?
    – sfdcfox
    Commented May 30, 2021 at 3:07
  • yes, its a datetime field, updated the question.
    – Nick
    Commented May 30, 2021 at 3:12

1 Answer 1

3

In Apex, just take away 24 hours:

Date last24Hours = DateTime.now().addDays(-1);
Employee__c[] employeesLast24Hours = [
  SELECT My_Date__c 
  FROM Employee__c 
  WHERE My_Date__c >= :last24Hours
];

If you really want the last 24 hours without a variable, it should look more like:

SELECT My_Date__c 
FROM Employee__c
WHERE My_Date__c = TODAY OR
 (My_Date__c = YESTERDAY AND HOUR_IN_DAY(My_Date__c) > 17)

Remember to use 24 hour format; PM hours are the hour plus 12 (5 + 12 = 17).

8
  • the first query, i'm not sure this will work because I'm looking for a specific time like 5pm the second query looks promising but one question where are you checking to see if the my_date is within past 24 hours (> yesterday at 5pm and <= today at 5pm) ?
    – Nick
    Commented May 30, 2021 at 3:28
  • 1
    @NickKahn now() returns the current time, accurate to the millisecond. Adding -1 days will take you to exactly 24 hours ago. The second one, we're looking for everything "today" and everything "yesterday" after 5pm. If you also need to check for today up to 5pm, it'd be: (TODAY AND HOUR_IN_DAY(My_Date__c)<17) OR (YESTERDAY AND HOUR_IN_DAY(My_Date__c)>=17)
    – sfdcfox
    Commented May 30, 2021 at 3:32
  • Unexpected token '<'. here is what i got SELECT My_Date__c FROM Employee__c WHERE My_Date__c = (TODAY AND HOUR_IN_DAY(My_Date__c)<17) OR (YESTERDAY AND HOUR_IN_DAY(My_Date__c)>=17)
    – Nick
    Commented May 30, 2021 at 3:44
  • @NickKahn SOQL is strictly FIELD = VALUE. I see my previous comment had a typo or three. Try: (My_Date__c = TODAY AND HOUR_IN_DAY(My_Date__c)<17) OR (My_Date__c = YESTERDAY AND HOUR_IN_DAY(My_Date__c)>=17)
    – sfdcfox
    Commented May 30, 2021 at 3:54
  • I add convertTimeZone otherwise it was not catching the right number of hours. HOUR_IN_DAY(convertTimezone(My_Date__c))
    – Nick
    Commented May 30, 2021 at 15:51

You must log in to answer this question.

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