Tuesday, 13 March 2012

Find 'Day' & ‘Day Of Week’ From 'Date' in Salesforce.

There are many scenarios in salesforce where we need to find out day from date.
For example, for scheduling a job through system.schedule() method , we need  Day_of_week.





Date startDate = date.newInstance(0001, 1, 1);

List<String> daysList = new List<String>
{'null', 'Sunday' , 'Monday' , 'Tuesday' , 'Wednesday' , 'Thursday' , 'Friday','Saturday' }; 


Date dayForDate = system.today();

Integer remainder = Math.mod(startDate.daysBetween (dayForDate) , 7);
       

if(remainder==0){remainder=7;}
       

string calculatedDay = daysList.get(remainder);

system.debug('Day of week for dayForDate ---->'+remainder);


system.debug('day for dayForDate ----->'+ calculatedDay);

Tuesday, 21 February 2012

Get sObject Name from Record ID.....!!!!

Sometimes there are scenarios when we use

string urlID = ApexPages.currentPage().getParameters().get('id');

and develop the functionality based on urlID .

What should we do, if sometimes urlID gives ID of Object 'X' and sometimes it gives
ID of 'Y' based on business requirement?

Here is what I did....






 urlId=ApexPages.currentPage().getParameters().get('id');

 Map<String, Schema.SObjectType> gd = Schema.getGlobalDescribe();
            
 Map<String,String> keyPrefixMap = new Map<String,String>{};
            
 Set<String> keyPrefixSet = gd.keySet();
           
 for(String sObj : keyPrefixSet){
               
 Schema.DescribeSObjectResult r =  gd.get(sObj).getDescribe();
               
 String tempName = r.getName();             
               
 String tempPrefix = r.getKeyPrefix();
              
 keyPrefixMap.put(tempPrefix,tempName);
             
 }
            
             
 string objtempPrefix =urlId.subString(0,3);
             
 string objname =keyPrefixMap.get(objtempPrefix );
         
             
 system.debug('object name--------------->'+objname );




The first three chars of a record id refer to the sobject the record is based on.
 IF urlId is ID of X , objname will be 'X'
 IF urlId is ID of Y , objname will be 'y'