function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Raghu Cheruvu 1Raghu Cheruvu 1 

identifying salesforce records which were modified in the last 2 hours

Hi,

I am looking to identify salesforce records which were modified in the last 2 hours based on lastmodifeddate. Is there a datetime filter which can be used in SOQL to acheive this.
Best Answer chosen by Raghu Cheruvu 1
Zuinglio Lopes Ribeiro JúniorZuinglio Lopes Ribeiro Júnior
In that case, try like the code below:
 
List<Account> accounts = [SELECT Id, Name 
                          FROM Account 
                          WHERE LastModifiedDate >= TODAY 
                         AND HOUR_IN_DAY(LastModifiedDate) > 4];

system.debug(accounts);

You will have to specify the hour. i.e. If now it's 6 p.m. and I want to get all modified records within the last 2 hours, set it to > 4.
Is it clear?

Regards.

Don't forget to mark your thread as 'SOLVED' with the answer that best helps you.

All Answers

Zuinglio Lopes Ribeiro JúniorZuinglio Lopes Ribeiro Júnior
Hello,

Here is a example of how you can do it:
 
Datetime dt = Datetime.newInstanceGmt(System.today(), System.now().time());
dt = dt.addHours(-2);

List<Account> accounts = [SELECT Id, Name FROM Account WHERE LastModifiedDate >= : dt];

system.debug(accounts);

Regards.

Don't forget to mark your thread as 'SOLVED' with the answer that best helps you.
Zuinglio Lopes Ribeiro JúniorZuinglio Lopes Ribeiro Júnior
And you can also try like this if you want to the last 2 hours ignoring minutes and seconds:
 
Datetime actualDate = System.now();
Time tt = Time.newInstance((actualDate.hour() - 2) , 0, 0, 0);
Datetime dt = Datetime.newInstanceGmt(actualDate.date(), tt);

List<Account> accounts = [SELECT Id, Name FROM Account WHERE LastModifiedDate >= : dt];

system.debug(accounts);

 
Raghu Cheruvu 1Raghu Cheruvu 1
Hi,

Thanks for your response.

I am looking to use the SOQL as a extract query in a Process-Conf file for apex data loader command line interface. Is there a way the above approach can be used in a extract query for CLI.
Zuinglio Lopes Ribeiro JúniorZuinglio Lopes Ribeiro Júnior
In that case, try like the code below:
 
List<Account> accounts = [SELECT Id, Name 
                          FROM Account 
                          WHERE LastModifiedDate >= TODAY 
                         AND HOUR_IN_DAY(LastModifiedDate) > 4];

system.debug(accounts);

You will have to specify the hour. i.e. If now it's 6 p.m. and I want to get all modified records within the last 2 hours, set it to > 4.
Is it clear?

Regards.

Don't forget to mark your thread as 'SOLVED' with the answer that best helps you.
This was selected as the best answer