Tuesday, December 26, 2017

How to use Date Time Variable in Dynamic Query Salesforce

In some scenario you might have come across to fetch record with in some date time range. 
Here I am sharing some code for this. Suppose I am querying records from Minutes Object. There is two field Start_Time and End_Time present  in Minutes Object.
This is my page 

 <apex:inputField value="{!minute.Start_Time__c}" required="true" label="From Date"/>
 <apex:inputField value="{!minuteObj.End_Time__c}" required="true" label="To Date"/>
<apex:commandButton action="{!convertValidMinutesToUsage}" value="Process Minute's"/>

This is my controller 
public with sharing class ControllerValidMinutesToUsage {
     public Minute__c minute{get;set;}
     DateTime startDate;
     DateTime endDate;
     string query;

     public ControllerValidMinutesToUsage(){
            minute =  new Minute__c();
    }

    public void convertValidMinutesToUsage(){
       String sStartdate;
       String sEndDate;
       startDate = minute.Start_Time__c;
       sStartdate = startDate.format('yyyy-MM-dd\'T\'HH:mm:ss\'Z\'');
       endDate = minuteObj.End_Time__c+1;
       sEndDate = endDate.format('yyyy-MM-dd\'T\'HH:mm:ss\'Z\'');
       query = 'SELECT Start_Time__c ,End_Time__c, Is_Valid__c WHERE Is_Valid__c = false';
       query += ' AND Start_Time__c >='+sStartdate+' '+'AND Start_Time__c <='+sEndDate
       list<Minute__c> =  DateBase.query(query );
    }
}

No comments:

Post a Comment