Sometimes we need to use AJAX toolkit to do some SOQL/DML on Data from a custom button, which executes javascript. Here in this post we will just get current Datetime and then we will create datetime literal as per SOQL standard to fetch some records as per requirement.
For more information about SOQL date/datetime formats Click Here.
Where to Use :
This can be used when you need to fetch records where some datetime field is less/greater than current time. You can also update it to get records of last 1 hours, 2 hours etc.
Datetime Literal Javascript Methods :
1 2 3 4 5 6 7 8 9 10 11 |
function twoDigit(number) { var twodigit = number >= 10 ? number : "0"+number.toString(); return twodigit; } function getCurrentSOQLDateTimeLiteral() { var dt = new Date(); // Datetime can be updated here if needed. var soqlDTLiteral = dt.getUTCFullYear() +'-'+twoDigit(dt.getUTCMonth()+1)+'-'+twoDigit(dt.getUTCDate()); soqlDTLiteral += 'T' + twoDigit(dt.getUTCHours()) + ':' + twoDigit(dt.getUTCMinutes()) + ':' + twoDigit(dt.getUTCSeconds()); soqlDTLiteral += 'Z'; return soqlDTLiteral; } |
Use With Ajax toolkit Salesforce :
1 2 3 4 5 6 7 8 |
{!REQUIRESCRIPT("/soap/ajax/38.0/connection.js")} var currentDatetime = getCurrentSOQLDateTimeLiteral(); // Getting Account WHERE Date_Time__c field is greater than from now var query = "SELECT Id, Name FROM Account WHERE Date_Time__c > "+currentDatetime; var records = sforce.connection.query(query); alert("RECORDS HERE " + records.getArray("records")); |
Hope this will help when you are creating SOQL query string using javascript.
Use it wherever you can whether its javascript button, lightening component or anything, to save your time and be a speedy coder.