+ Start a Discussion
Bryan CerratiBryan Cerrati 

Isolating Time from DateTime class

hey guys im very new to programming in general, i dont know advanced techniques or anything but you all seem so generous and helpful so i thought id give it a shot. ok so here we go... i have a custom object that is a lead recieving platform from jungo. i need to write a trigger for leads that come in after buisness hours to send a specific message. i didnt see a way for the point and click tools to diferentiate the date from the time. it doesnt matter the date the leads will be coming in every day and all days. but leads that come in after 6pm est i woulld like to send specific messages and set specific tasks. 

i came to the conclusion that (i may be wrong and doing a terrible job) i would need to convert the datetime field of CreatedDate to a string, then use substringAfter(' ') to get just the time as a string. then from there i can use basic operators to compare to after hours times. 

i created a class with a method for just adding the time as a string to a field i created called time__c 

im not sure what i am doing wrong, so any advice will help 
 
public with sharing class timingClass 
{
	public static void createTimeStamp()
	{
		List<JungoLeadsFrc__JungoLeads__c> dateAndTime = [SELECT Id, CreatedDate, Time__c from JungoLeadsFrc__JungoLeads__c];
		
		
		for (JungoLeadsFrc__JungoLeads__c lead : dateAndTime)
		{
			String dateNtime = string.valueof(dateAndTime.CreatedDate);
			String s2 = dateNtime.substringBefore(' ');
			lead.Time = s2;
		}
		
		update dateAndTime;
	}
	
}

i am obviously going to have to create this as a after trigger but i am literally trying to get a feel for how salesforce works, and like i said before i know absolutly nothing about coding. 
Best Answer chosen by Bryan Cerrati
Nayana KNayana K
public class zillowLeadFollowup
{
	
	public void onAfterInsert(List<JungoLeadsFrc__JungoLeads__c> lstNewLead)
	{
		sendAlertAfter6pmBefore9am(lstNewLead);	
	}

	private void sendAlertAfter6pmBefore9am(List<JungoLeadsFrc__JungoLeads__c> lstNewLead)
	{
		List<Messaging.SingleEmailMessage> lstMail = new List<Messaging.SingleEmailMessage>();
		List<JungoLeadsFrc__JungoLeads__c> lstLeadToUpdate = new List<JungoLeadsFrc__JungoLeads__c>();
		List<Task> lstTaskToInsert = new List<task>();
		
		for(JungoLeadsFrc__JungoLeads__c objLead: lstNewLead)
		{
			if(objLead.JungoLeadsFrc__Zillow_Recipient_Email__c != null) 
			{
				/* 1. We should never hardcode Ids; because in production Ids may not be same unless it is full copy sandbox.
				You can query owner Id based on User name(or as per your condition) before this for loop and assign ownerId dynamically here
				Let me know on which basis you want to assign ownerId, so that I can modify the code later
				
				2. We should never do DML operations inside a loop, instead keep a list, add the instance into list and update the list outside for loop.
				I will share you apex commandaments link below.
				*/
				lstLeadToUpdate.add(new JungoLeadsFrc__JungoLeads__c(Id = objLead.Id, OwnerId = '000000000000', JungoLeadsFrc__Stage__c = 'New',
																	JungoLeadsFrc__LeadSource__c = 'Zillow'));
				
				// Step 1: Create a new Email
				Messaging.SingleEmailMessage objMail = new Messaging.SingleEmailMessage();
				List<String> lstSendTo = new List<String>(); 
				List<String> lstCcTo = new List<String>();
				List<String> lstSendBcc = new List<String>();
				
				// I assume you want to send email to the leads created after 6pm and before 9am
				if(objLead.CreatedDate.hour() >= 18 || objLead.CreatedDate.hour() <= 8 )
				{
					
					  // Step 2: Set list of people who should get the email
					  lstSendTo.add(objLead.JungoLeadsFrc__Zillow_Recipient_Email__c);
					  objMail.setToAddresses(lstSendTo);
					
					  // Step 3: Set who the email is sent from
					  //objMail.setReplyTo('nayana@test.com');
					  objMail.setReplyTo('REPLACE_WITH_VALID_EMAIL_HERE');
					  objMail.setSenderDisplayName('Bryan Cerrati');
					
					  // (Optional) Set list of people who should be CC'ed
					  lstCcTo.add('REPLACE_WITH_VALID_EMAIL_HERE');
					  objMail.setCcAddresses(lstCcTo);

					  // Step 4. Set email contents - you can use variables!
					  objMail.setSubject('Specific Message');
					  // frame body message with valid message
					  String body = 'Dear ' + objLead.LastName + ', ';
					  body += 'I confess this will come as a surprise to you.';
					  body += 'I am John Alliston CEO of the Bank of Nigeria.';
					  body += 'I write to request your cooperation in this ';
					  body += 'urgent matter as I need a foreign partner ';
					  body += 'in the assistance of transferring $47,110,000 ';
					  body += 'to a US bank account. Please respond with ';
					  body += 'your bank account # so I may deposit these funds.';
					  objMail.setHtmlBody(body);
					
					  // Step 5. Add your email to the master list
					  mails.add(objMail); 
					  
					  /*Task: After Hours ALERT (Any specific reason for hardcoding 000000000 id in WhoId? 
					  I am not familiar with this '0000000000' id. Best practice is not to hardcode id )**/
					  lstTaskToInsert.add(new Task(Subject = 'Lead Revieved After Hours!', 
													Priority = 'High', 
													Status = 'Not Started', 
													IsReminderSet = true, 
													ReminderDateTime = System.today() + 1, 
													Description = 'Call Lead Immediatly, Lead Created at ' + objLead.CreatedDate + ' by the name of ' 
													+ objLead.JungoLeadsFrc__Firstname__c + ' ' + objLead.JungoLeadsFrc__LastName__c,
													WhoId = '0000000000000'));
					
				}
				else // Create Email to leads created 9am to 5pm
				{
					lstSendTo.add(objLead.JungoLeadsFrc__EmailAddress__c);
					objMail.SetToAddresses(lstSendTo);
					objMail.setReplyTo('help@unitedmortgage.com');
					objMail.setSenderDisplayName('Jason Frangoulis');
					
					lstSendBcc.add('bcerrati@gmail.com');
					objMail.setBccAddresses(lstSendBcc);
					//objMail.setBccAddresses('bcerrati@unitedmortgage.com');
					objMail.setSubject(objLead.JungoLeadsFrc__FirstName__c + ' Welcome to United Mortgage');
					String body = 'Dear ' + objLead.JungoLeadsFrc__FirstName__c + ' ' + objLead.JungoLeadsFrc__LastName__c +',';
					body =+ '';
					objMail.setHtmlBody(body);
					lstMail.add(objMail);
					
					//Task "Call New Lead"
					lstTaskToInsert.add(new Task
											(
												Subject = 'Call New Lead', 
												Priority = 'Normal', 
												Status = 'Not Started', 
												IsReminderSet = true, 
												ReminderDateTime = system.now(), 
												WhoId = '000000000000',
												Description = 'Call Lead Immediatly, Lead Created at ' + objLead.CreatedDate
											)
										);
				
					// Task "NEW LEAD RECIEVED"
					lstTaskToInsert.add(new Task
											(
												Subject = 'NEW LEAD RECIEVED',
												Priority = 'Normal',
												Status = 'Not Started',
												IsReminderSet = true,
												Description = 'New Lead Recieved at ' + objLead.CreatedDate + '. with jungo lead ID of ' + objLead.Name,
												WhoId = '000000000000'
											)
										);
				}
			}
			else
			{
				Messaging.SingleEmailMessage noEmail = new Messaging.SingleEmailMessage();
				List<String> lstSendTo = new List<String>();
				lstSendTo.add('help@unitedmortgage.com');
				noEmail.setToAddresses(lstSendTo);
				noEmail.setReplyTo('help@unitedmortgage.com');
				noEmail.setSenderDisplayName('Lead Warning');
				List<String> lstSendBcc = new List<String>();
				lstSendBcc.add('bcerrati@gmail.com');
				noEmail.setBccAddresses(lstSendBcc);
				//noEmail.setBccAddresses = new String [] {'bcerrati@gmail.com'};
				noEmail.setSubject('WARNING! Lead inserted with no email!');
				String body = 'Dear Jason, Zillow has done the unthinkable and sent over ';
				body += 'a lead that does not contain an email address. Please contact ';
				body += 'Clayton from Zillow if this lead turns out to be a phoney. He can ';
				body += 'can be reached at claytonf@zillowgroup.com. ';
				noEmail.setHtmlBody(body);
				lstMail.add(noEmail);
			}
		
		}
		
		//send email
		if(!lstMail.isEmpty())
			Messaging.sendEmail(lstMail);
		if(!lstTaskToInsert.isEmpty())
			insert lstTaskToInsert;
		if(!lstLeadToUpdate.isEmpty())
			update lstLeadToUpdate;
	}
}


Trigger :

trigger JungoLeadTrigger on JungoLeadsFrc__JungoLeads__c(after insert)
{
	zillowLeadFollowup objHandler = new zillowLeadFollowup();
	if(Trigger.isAfter && Trigger.isInsert)
		objHandler.onAfterInsert(Trigger.New);
}

 

All Answers

Nayana KNayana K
https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_methods_system_datetime.htm

You can refer above link for date methods.

I can give you pseudo kind of code.

public class JungoLeadTriggerHandler
{
public void onAfterInsert(List<JungoLeadsFrc__JungoLeads__c> lstNewLead)
{
 sendAlertAfter6pm(lstNewLead);
}

private void sendAlertAfter6pm(List<JungoLeadsFrc__JungoLeads__c> lstNewLead)
{
for(JungoLeadsFrc__JungoLeads__c objLead: lstNewLead)
{
if(objLead.CreatedDate.hour() >= 18)
{
// Add a code to send email. 
}
}
}

}


Trigger :

trigger JungoLeadTrigger on JungoLeadsFrc__JungoLeads__c(after insert)
{
JungoLeadHandler objHandler = new JungoLeadHandler();
if(Trigger.isAfter && Trigger.isInsert)
 objHandler.onAfterInsert(Trigger.New);
}

 
Dilip_VDilip_V
Hey Bryan,

Try this class
 
public with sharing class timingClass 
{
	public static void createTimeStamp(Llist<JungoLeadsFrc__JungoLeads__c> Leads )
	{
	
		for (JungoLeadsFrc__JungoLeads__c lead : Leads)
		{
			Datetime Dt= dateAndTime.CreatedDate;
			Date myDate = date.newinstance(dT.year(), dT.month(), dT.day());
			lead.Time __C= String.valueof(myDate);
                        
		}
		
		update Leads;
	}
	
}

and trigger
 
trigger JungoLeadTrigger on JungoLeadsFrc__JungoLeads__c(after insert)
{
if(Trigger.isAfter && Trigger.isInsert)
{
timingClass.createTimeStamp(Trigger.new);
}
}

Let me know if it helps.

Make it as best answer if it helps.

Thanks.

 
Bryan CerratiBryan Cerrati
this is fantastic... i dont know what the logic is aiming at though.
if(objLead.CreatedDate.hour() >= 18)
so if the created date is greater then or equal to 18? im not sure how that represents 6pm

i need it to work at 9am to 6pm. is there a way to add a range. 
 
Bryan CerratiBryan Cerrati
hey buddy.... thank you so much for that i am going to test that immediatly. i get it... populate the new instance with the created date. im going to change it to time variables because i do not need the date i actually want to throw the date out. 
Nayana KNayana K
if(objLead.CreatedDate.hour() >= 18) means graeter than equal to 6pm. If you want a range (9am to 6pm)  then  


if(objLead.CreatedDate.hour() >= 9 && objLead.CreatedDate.hour() <= 18) which 
Nayana KNayana K
public class JungoLeadTriggerHandler
{
	public void onAfterInsert(List<JungoLeadsFrc__JungoLeads__c> lstNewLead)
	{
		sendAlertAfter6pmBefore9am(lstNewLead);
	}

	private void sendAlertAfter6pmBefore9am(List<JungoLeadsFrc__JungoLeads__c> lstNewLead)
	{
		List<Messaging.SingleEmailMessage> lstMail = new List<Messaging.SingleEmailMessage>();
		for(JungoLeadsFrc__JungoLeads__c objLead: lstNewLead)
		{
			// I assume you want to send email to the leads created after 6pm and before 9am
			if(objLead.CreatedDate.hour() >= 18 || objLead.CreatedDate.hour() <= 9 )
			{
				if(objLead.Email != null) 
				{
				  // Step 1: Create a new Email
				  Messaging.SingleEmailMessage objMail = new Messaging.SingleEmailMessage();
				
				  // Step 2: Set list of people who should get the email
				  List<String> lstSendTo = new List<String>();
				  lstSendTo.add(objLead.Email);
				  objMail.setToAddresses(lstSendTo);
				
				  // Step 3: Set who the email is sent from
				  //objMail.setReplyTo('nayana@test.com');
				  objMail.setReplyTo('REPLACE_WITH_VALID_EMAIL_HERE');
				  objMail.setSenderDisplayName('Bryan Cerrati');
				
				  // (Optional) Set list of people who should be CC'ed
				  List<String> lstCcTo = new List<String>();
				  lstCcTo.add('REPLACE_WITH_VALID_EMAIL_HERE');
				  objMail.setCcAddresses(lstCcTo);

				  // Step 4. Set email contents - you can use variables!
				  objMail.setSubject('Specific Message');
				  // frame body message with valid message
				  String body = 'Dear ' + objLead.LastName + ', ';
				  body += 'I confess this will come as a surprise to you.';
				  body += 'I am John Alliston CEO of the Bank of Nigeria.';
				  body += 'I write to request your cooperation in this ';
				  body += 'urgent matter as I need a foreign partner ';
				  body += 'in the assistance of transferring $47,110,000 ';
				  body += 'to a US bank account. Please respond with ';
				  body += 'your bank account # so I may deposit these funds.';
				  objMail.setHtmlBody(body);
				
				  // Step 5. Add your email to the master list
				  mails.add(objMail); 
				}
			}
		}
		
		//send email
		if(!lstMail.isEmpty())
			Messaging.sendEmail(lstMail);
	}
}


Trigger :

trigger JungoLeadTrigger on JungoLeadsFrc__JungoLeads__c(after insert)
{
	JungoLeadHandler objHandler = new JungoLeadHandler();
	if(Trigger.isAfter && Trigger.isInsert)
		objHandler.onAfterInsert(Trigger.New);
}
Bryan CerratiBryan Cerrati
NAYANA!!!! YOU ARE A GENIOUS!!! i have literally learned more from you then i have in a few hours of turirial CBT. can we be best friends?

i ran into an issue.

i dont under stand the line:
mails.add(objMail);

you listed it as number 5. as add you email to master list... im not sure what you mean by that?

and i get a complile error of "mails variable is not found" but im not sure what the assignment should have been because i do not understand the goal of the line. 
Nayana KNayana K
Replace that line with lstMail.add(objMail);
Bryan CerratiBryan Cerrati
ok i understand... i need to send the overall list created a new instance of. 

thank you nayana! i have activated it inside of my sandbox and i will let you know what is the end result. thank you again i will followup tommorrow on the progress. 
Nayana KNayana K
Sure, let me know if you face any issues.
Bryan CerratiBryan Cerrati
thank you so much, i am just having a dilema as i cant figure out if i need to create another loop to do field updates in the class. if i add another loop before the first one.
 
List<Messaging.SingleEmailMessage> lstMail = new List<Messaging.SingleEmailMessage>();
for(JungoLeadsFrc__JungoLeads__c objLead: lstNewLead)

are both loops going to run each time or do i have to crete some kind of break? 

i had to add an else to the whole loop as i need diffrent messages to be sent during the hours of 9-5 so it got quite big, but i also needed to create tasks diffrent ones for 9-5 and diffrent ones for 6-8.59am so i set them in the if's

heres the code i have so far. 
 
public with sharing class zillowLeadFollowup 
{
	// encase private method (what ever its called) hahahahahhahahah
	public void onAfterInsert(List<JungoLeadsFrc__JungoLeads__c> lstNewLead)
	{
		sendAlertAfter6pmBefore9am(lstNewLead);
	}

	private void sendAlertAfter6pmBefore9am(List<JungoLeadsFrc__JungoLeads__c> lstNewLead)
	{
		for(JungoLeadsFrc__JungoLeads__c objField: lstNewLead)
		{
			if(objField.JungoLeadsFrc__Zillow_Recipient_Email__c != null)
			{
				objField.OwnerId = '000000000000';
				objField.JungoLeadsFrc__Stage__c = 'New';
				objField.JungoLeadsFrc__LeadSource__c = 'Zillow';
				update objField;
			}
		}
		
		List<Messaging.SingleEmailMessage> lstMail = new List<Messaging.SingleEmailMessage>();
		for(JungoLeadsFrc__JungoLeads__c objLead: lstNewLead)
		{				
			
			// leads created after 6pm and before 9am
			if(objLead.CreatedDate.hour() >= 18 || objLead.CreatedDate.hour() <= 8)
			{
			
				//Task: After Hours ALERT
				Task afterHourTask = new Task
				(
					Subject = 'Lead Revieved After Hours!', 
					Priority = 'High', 
					Status = 'Not Started', 
					IsReminderSet = true, 
					ReminderDateTime = system.today() + 1, 
					Description = 'Call Lead Immediatly, Lead Created at ' + objLead.CreatedDate + ' by the name of ' 
					+ objLead.JungoLeadsFrc__Firstname__c + ' ' + objLead.JungoLeadsFrc__LastName__c,
					WhoId = '0000000000000'
				);

				
				//Email
				if(objLead.JungoLeadsFrc__EmailAddress__c != null) 
				{
				  Messaging.SingleEmailMessage objMail = new Messaging.SingleEmailMessage();
				  List<String> lstSendTo = new List<String>();
				  lstSendTo.add(objLead.JungoLeadsFrc__EmailAddress__c);
				  objMail.setToAddresses(lstSendTo);
				  objMail.setReplyTo('help@unitedmortgage.com');
				  objMail.setSenderDisplayName('Jason Frangoulis');
				  objMail.setSubject(objLead.JungoLeadsFrc__FirstName__c + ' Welcome to United Mortgage');
				  String body = 'Dear ' + objLead.JungoLeadsFrc__FirstName__c + ' ' + objLead.JungoLeadsFrc__LastName__c + ', ';
				  body += 'You have contacted me after hours, which are 9am to 5pm EST. ';
				  body += 'I will be contacting you first thing in the morning to follow ';
				  body += 'up with your inquiry. If you would like ';
				  body += 'to specify a diffrent callback time please reply to  ';
				  body += 'this email with a Date and Time convienient to you. ';
				  body += 'Please do not hesitate to reply with any questions or ';
				  body += 'concerns you may have i will be glad to answer them. <P> ';
				  body += 'Sincerly, Jason Frangoulis';
				  objMail.setHtmlBody(body);
				  lstMail.add(objMail); 
				}
				
				else
				{
					Messaging.SingleEmailMessage noEmail = new Messaging.SingleEmailMessage();
					List<String> lstSendTo = new List<String>();
					lstSendTo.add('help@unitedmortgage.com');
					noEmail.setToAddresses(lstSendTo);
					noEmail.setReplyTo('help@unitedmortgage.com');
					noEmail.setSenderDisplayName('Lead Warning');
					List<String> lstSendBcc = new List<String>();
					lstSendBcc.add('bcerrati@gmail.com');
					noEmail.setBccAddresses(lstSendBcc);
					//noEmail.setBccAddresses = new String [] {'bcerrati@gmail.com'};
					noEmail.setSubject('WARNING! Lead inserted with no email!');
					String body = 'Dear Jason, Zillow has done the unthinkable and sent over ';
					body += 'a lead that does not contain an email address. Please contact ';
					body += 'Clayton from Zillow if this lead turns out to be a phoney. He can ';
					body += 'can be reached at claytonf@zillowgroup.com. ';
					noEmail.setHtmlBody(body);
					lstMail.add(noEmail);
				}
			}
			
			
			else // Create Email to leads created 9am to 5pm
			{
				
				//Task "Call New Lead"
				Task callNewLead = new Task
				(
					Subject = 'Call New Lead', 
					Priority = 'Normal', 
					Status = 'Not Started', 
					IsReminderSet = true, 
					ReminderDateTime = system.now(), 
					WhoId = '000000000000',
					Description = 'Call Lead Immediatly, Lead Created at ' + objLead.CreatedDate
				);
				
				// Task "NEW LEAD RECIEVED"
				Task newLeadRecieved = new Task
				(
					Subject = 'NEW LEAD RECIEVED',
					Priority = 'Normal',
					Status = 'Not Started',
					IsReminderSet = true,
					Description = 'New Lead Recieved at ' + objLead.CreatedDate + '. with jungo lead ID of ' + objLead.Name,
					WhoId = '000000000000'
				);
				
				if(objLead.JungoLeadsFrc__EmailAddress__c != null)
				{
					Messaging.SingleEmailMessage objMail = new Messaging.SingleEmailMessage();
					List<string> lstSendTo = new List<String>();
					lstSendTo.add(objLead.JungoLeadsFrc__EmailAddress__c);
					objMail.SetToAddresses(lstSendTo);
					objMail.setReplyTo('help@unitedmortgage.com');
					objMail.setSenderDisplayName('Jason Frangoulis');
					List<String> lstSendBcc = new List<String>();
					lstSendBcc.add('bcerrati@gmail.com');
					objMail.setBccAddresses(lstSendBcc);
					//objMail.setBccAddresses('bcerrati@unitedmortgage.com');
					objMail.setSubject(objLead.JungoLeadsFrc__FirstName__c + ' Welcome to United Mortgage');
					String body = 'Dear ' + objLead.JungoLeadsFrc__FirstName__c + ' ' + objLead.JungoLeadsFrc__LastName__c +',';
					body =+ '';
					objMail.setHtmlBody(body);
					lstMail.add(objMail);
				}
				
				else
				{
					Messaging.SingleEmailMessage noEmail = new Messaging.SingleEmailMessage();
					List<String> lstSendTo = new List<String>();
					lstSendTo.add('help@unitedmortgage.com');
					noEmail.setBccAddresses(lstSendTo);
					//noEmail.setToAddresses = new String[] {'help@unitedmortgage.com'};
					noEmail.setReplyTo('help@unitedmortgage.com');
					noEmail.setSenderDisplayName('Lead Warning');
					List<String> lstSendBcc = new List<String>();
					lstSendBcc.add('bcerrati@gmail.com');
					noEmail.setBccAddresses(lstSendBcc);
					//noEmail.setBccAddresses = new String [] {'bcerrati@gmail.com'};
					noEmail.setSubject('WARNING! Lead inserted with no email!');
					String body = 'Dear Jason, Zillow has done the unthinkable and sent over ';
					body += 'a lead that does not contain an email address. Please contact ';
					body += 'Clayton from Zillow if this lead turns out to be a phoney. He can ';
					body += 'can be reached at claytonf@zillowgroup.com. ';
					noEmail.setHtmlBody(body);
					lstMail.add(noEmail);
				}
			}
		}
		
		//send email
		if(!lstMail.isEmpty())
		{
			Messaging.sendEmail(lstMail);
		}
	}
}

i put the new for loop outside of the if that contins any hours because i need the field updates to execute no matter what. reguarless of time. 

thaank you again. 
Nayana KNayana K
public class zillowLeadFollowup
{
	
	public void onAfterInsert(List<JungoLeadsFrc__JungoLeads__c> lstNewLead)
	{
		sendAlertAfter6pmBefore9am(lstNewLead);	
	}

	private void sendAlertAfter6pmBefore9am(List<JungoLeadsFrc__JungoLeads__c> lstNewLead)
	{
		List<Messaging.SingleEmailMessage> lstMail = new List<Messaging.SingleEmailMessage>();
		List<JungoLeadsFrc__JungoLeads__c> lstLeadToUpdate = new List<JungoLeadsFrc__JungoLeads__c>();
		List<Task> lstTaskToInsert = new List<task>();
		
		for(JungoLeadsFrc__JungoLeads__c objLead: lstNewLead)
		{
			if(objLead.JungoLeadsFrc__Zillow_Recipient_Email__c != null) 
			{
				/* 1. We should never hardcode Ids; because in production Ids may not be same unless it is full copy sandbox.
				You can query owner Id based on User name(or as per your condition) before this for loop and assign ownerId dynamically here
				Let me know on which basis you want to assign ownerId, so that I can modify the code later
				
				2. We should never do DML operations inside a loop, instead keep a list, add the instance into list and update the list outside for loop.
				I will share you apex commandaments link below.
				*/
				lstLeadToUpdate.add(new JungoLeadsFrc__JungoLeads__c(Id = objLead.Id, OwnerId = '000000000000', JungoLeadsFrc__Stage__c = 'New',
																	JungoLeadsFrc__LeadSource__c = 'Zillow'));
				
				// Step 1: Create a new Email
				Messaging.SingleEmailMessage objMail = new Messaging.SingleEmailMessage();
				List<String> lstSendTo = new List<String>(); 
				List<String> lstCcTo = new List<String>();
				List<String> lstSendBcc = new List<String>();
				
				// I assume you want to send email to the leads created after 6pm and before 9am
				if(objLead.CreatedDate.hour() >= 18 || objLead.CreatedDate.hour() <= 8 )
				{
					
					  // Step 2: Set list of people who should get the email
					  lstSendTo.add(objLead.JungoLeadsFrc__Zillow_Recipient_Email__c);
					  objMail.setToAddresses(lstSendTo);
					
					  // Step 3: Set who the email is sent from
					  //objMail.setReplyTo('nayana@test.com');
					  objMail.setReplyTo('REPLACE_WITH_VALID_EMAIL_HERE');
					  objMail.setSenderDisplayName('Bryan Cerrati');
					
					  // (Optional) Set list of people who should be CC'ed
					  lstCcTo.add('REPLACE_WITH_VALID_EMAIL_HERE');
					  objMail.setCcAddresses(lstCcTo);

					  // Step 4. Set email contents - you can use variables!
					  objMail.setSubject('Specific Message');
					  // frame body message with valid message
					  String body = 'Dear ' + objLead.LastName + ', ';
					  body += 'I confess this will come as a surprise to you.';
					  body += 'I am John Alliston CEO of the Bank of Nigeria.';
					  body += 'I write to request your cooperation in this ';
					  body += 'urgent matter as I need a foreign partner ';
					  body += 'in the assistance of transferring $47,110,000 ';
					  body += 'to a US bank account. Please respond with ';
					  body += 'your bank account # so I may deposit these funds.';
					  objMail.setHtmlBody(body);
					
					  // Step 5. Add your email to the master list
					  mails.add(objMail); 
					  
					  /*Task: After Hours ALERT (Any specific reason for hardcoding 000000000 id in WhoId? 
					  I am not familiar with this '0000000000' id. Best practice is not to hardcode id )**/
					  lstTaskToInsert.add(new Task(Subject = 'Lead Revieved After Hours!', 
													Priority = 'High', 
													Status = 'Not Started', 
													IsReminderSet = true, 
													ReminderDateTime = System.today() + 1, 
													Description = 'Call Lead Immediatly, Lead Created at ' + objLead.CreatedDate + ' by the name of ' 
													+ objLead.JungoLeadsFrc__Firstname__c + ' ' + objLead.JungoLeadsFrc__LastName__c,
													WhoId = '0000000000000'));
					
				}
				else // Create Email to leads created 9am to 5pm
				{
					lstSendTo.add(objLead.JungoLeadsFrc__EmailAddress__c);
					objMail.SetToAddresses(lstSendTo);
					objMail.setReplyTo('help@unitedmortgage.com');
					objMail.setSenderDisplayName('Jason Frangoulis');
					
					lstSendBcc.add('bcerrati@gmail.com');
					objMail.setBccAddresses(lstSendBcc);
					//objMail.setBccAddresses('bcerrati@unitedmortgage.com');
					objMail.setSubject(objLead.JungoLeadsFrc__FirstName__c + ' Welcome to United Mortgage');
					String body = 'Dear ' + objLead.JungoLeadsFrc__FirstName__c + ' ' + objLead.JungoLeadsFrc__LastName__c +',';
					body =+ '';
					objMail.setHtmlBody(body);
					lstMail.add(objMail);
					
					//Task "Call New Lead"
					lstTaskToInsert.add(new Task
											(
												Subject = 'Call New Lead', 
												Priority = 'Normal', 
												Status = 'Not Started', 
												IsReminderSet = true, 
												ReminderDateTime = system.now(), 
												WhoId = '000000000000',
												Description = 'Call Lead Immediatly, Lead Created at ' + objLead.CreatedDate
											)
										);
				
					// Task "NEW LEAD RECIEVED"
					lstTaskToInsert.add(new Task
											(
												Subject = 'NEW LEAD RECIEVED',
												Priority = 'Normal',
												Status = 'Not Started',
												IsReminderSet = true,
												Description = 'New Lead Recieved at ' + objLead.CreatedDate + '. with jungo lead ID of ' + objLead.Name,
												WhoId = '000000000000'
											)
										);
				}
			}
			else
			{
				Messaging.SingleEmailMessage noEmail = new Messaging.SingleEmailMessage();
				List<String> lstSendTo = new List<String>();
				lstSendTo.add('help@unitedmortgage.com');
				noEmail.setToAddresses(lstSendTo);
				noEmail.setReplyTo('help@unitedmortgage.com');
				noEmail.setSenderDisplayName('Lead Warning');
				List<String> lstSendBcc = new List<String>();
				lstSendBcc.add('bcerrati@gmail.com');
				noEmail.setBccAddresses(lstSendBcc);
				//noEmail.setBccAddresses = new String [] {'bcerrati@gmail.com'};
				noEmail.setSubject('WARNING! Lead inserted with no email!');
				String body = 'Dear Jason, Zillow has done the unthinkable and sent over ';
				body += 'a lead that does not contain an email address. Please contact ';
				body += 'Clayton from Zillow if this lead turns out to be a phoney. He can ';
				body += 'can be reached at claytonf@zillowgroup.com. ';
				noEmail.setHtmlBody(body);
				lstMail.add(noEmail);
			}
		
		}
		
		//send email
		if(!lstMail.isEmpty())
			Messaging.sendEmail(lstMail);
		if(!lstTaskToInsert.isEmpty())
			insert lstTaskToInsert;
		if(!lstLeadToUpdate.isEmpty())
			update lstLeadToUpdate;
	}
}


Trigger :

trigger JungoLeadTrigger on JungoLeadsFrc__JungoLeads__c(after insert)
{
	zillowLeadFollowup objHandler = new zillowLeadFollowup();
	if(Trigger.isAfter && Trigger.isInsert)
		objHandler.onAfterInsert(Trigger.New);
}

 
This was selected as the best answer
Nayana KNayana K
https://developer.salesforce.com/blogs/developer-relations/2015/01/apex-best-practices-15-apex-commandments.html
Bryan CerratiBryan Cerrati
thats excellent...

ohhhh i just added zeros as a place holder... and i dont want to use and variables for the user. it will be very specific whom will be assigned... and the creator isnt nessicarily the owner. so i just hardcoded it in. 

creating a list for the tasks outside the loop at 
List<Task> lstTaskToInsert = new List<task>();

i have 2 tasks assigned to be created in the first main else. that wont be a problem? are they 2 new objects?

thanx for the link i am going to print it out and put it on my cubicle...thank you :-)

now i just need to lear how to write a test for this class and i should be good. everything seems great from here. 
Nayana KNayana K
'i have 2 tasks assigned to be created in the first main else. that wont be a problem? are they 2 new objects?' 
- No issues in this. It should actually coded in this way. First, create a list instance, then add individual task instanced to this list and after the loop do DML operation. (which means in bulk you are handling code)
Imagine you are creating a space(List<Task> lstTaskToInsert) to hold records which you are going to insert in bulk. In salesforce bulk handling is important.
And then in for loop, you are creating a new Task record (new Task(.....)) and adding to this space.After the loop collections are records resides in lstTaskToInsert which you will insert at the end. 


 
Bryan CerratiBryan Cerrati
ok excellent... thats fantastic so it is correct the way you explained it to me initially. i see most dml can be done with creating a list first and adding objects into it. thats great. 

i have another question... i am writing out a test class, but createdDate cannot be written... so im not sure how i can test any of the parts that rely on created date. which is 40% of the code.
Nayana KNayana K
Refer this post, may helpful : http://salesforce.stackexchange.com/questions/62/unit-testing-code-which-has-logic-around-the-createddate.
 
Bryan CerratiBryan Cerrati
yeah thats what i found too that exact link... i cannot get the section coverd:
if(objLead.CreatedDate.hour() >= 18 || objLead.CreatedDate.hour() <= 8)

i know this executes in sandbox ive tested it physically. 

the test is not taking the time into consideration... so i dont know if its the test class or the class
 
@isTest 
private class jungoLeadFollowupTest 
{

	@isTest static void zillowNull() 
	{
		Time myTime = Time.newInstance(10, 0, 0, 0);
		Date myDate = Date.newInstance(2016, 10, 5);
		DateTime dt = DateTime.newInstance(myDate, myTime);		
		JungoLeadsFrc__JungoLeads__c newLead = new JungoLeadsFrc__JungoLeads__c(
		JungoLeadsFrc__Zillow_Recipient_Email__c = null);
		insert newLead;
        Test.setCreatedDate(newLead.Id, dt);
		
	}
	
	@isTest static void zillowNotNull()
	{
		Time myTime = Time.newInstance(10, 0, 0, 0);
		Date myDate = Date.newInstance(2016, 10, 4);
		DateTime dt = DateTime.newInstance(myDate, myTime);
		JungoLeadsFrc__JungoLeads__c newLead = new JungoLeadsFrc__JungoLeads__c(
		JungoLeadsFrc__Zillow_Recipient_Email__c ='jfrangoulis@unitedmortgage.com');
		insert newLead;
		Test.setCreatedDate(newLead.Id, dt);
		
		
		
	}
	@isTest static void email()
	{
		Time myTime = Time.newInstance(22, 0, 0, 0);
		Date myDate = Date.newInstance(2016, 10, 4);
		DateTime dt = DateTime.newInstance(myDate, myTime);
		JungoLeadsFrc__JungoLeads__c newLead = new JungoLeadsFrc__JungoLeads__c(
		JungoLeadsFrc__Zillow_Recipient_Email__c ='jfrangoulis@unitedmortgage.com',
		JungoLeadsFrc__EmailAddress__c = null);
		insert newLead;
		Test.setCreatedDate(newLead.Id, dt);
	}
	
		@isTest static void emailnull()
	{
		Time myTime = Time.newInstance(22, 0, 0, 0);
		Date myDate = Date.newInstance(2016, 10, 4);
		DateTime dt = DateTime.newInstance(myDate, myTime);
		JungoLeadsFrc__JungoLeads__c newLead = new JungoLeadsFrc__JungoLeads__c(
		JungoLeadsFrc__EmailAddress__c = 'jfrangoulis@unitedmortgage.com',
		JungoLeadsFrc__Zillow_Recipient_Email__c = null);
		insert newLead;
		Test.setCreatedDate(newLead.Id, dt);
		
	}

}
i can execute all methods and none of the following is included in the test. 
 
if(objLead.CreatedDate.hour() >= 18 || objLead.CreatedDate.hour() <= 8)
			{
			
				//Task: After Hours ALERT
				lstTaskToInsert.add(new Task(
					Subject = 'Lead Recieved After Hours!', 
					Priority = 'High', 
					Status = 'Not Started', 
					IsReminderSet = true, 
					ReminderDateTime = system.today() + 1, 
					Description = 'Call Lead Immediatly, Lead Created at ' 
					+ objLead.CreatedDate + ' by the name of ' 
					+ objLead.JungoLeadsFrc__Firstname__c + ' ' 
					+ objLead.JungoLeadsFrc__LastName__c,
					WhoId = '0051a000000QX68'));

				
				//Email
				if(objLead.JungoLeadsFrc__EmailAddress__c != null) 
				{
				  Messaging.SingleEmailMessage objMail = new Messaging.SingleEmailMessage();
				  List<String> lstSendTo = new List<String>();
				  lstSendTo.add(objLead.JungoLeadsFrc__EmailAddress__c);
				  objMail.setToAddresses(lstSendTo);
				  objMail.setReplyTo('jfrangoulis@unitedmortgage.com');
				  objMail.setSenderDisplayName('Jason Frangoulis');
				  objMail.setSubject(objLead.JungoLeadsFrc__FirstName__c 
				  + ' Welcome to United Mortgage');
				  String body = 'Dear ' + objLead.JungoLeadsFrc__FirstName__c 
				  + ' ' + objLead.JungoLeadsFrc__LastName__c + ', ';
				  body += 'You have contacted me after hours, which are 9am to 5pm EST. ';
				  body += 'I will be contacting you first thing in the morning to follow ';
				  body += 'up with your inquiry. If you would like ';
				  body += 'to specify a diffrent callback time please reply to  ';
				  body += 'this email with a Date and Time convienient to you. ';
				  body += 'Please do not hesitate to reply with any questions or ';
				  body += 'concerns you may have i will be glad to answer them. <P> ';
				  body += 'Sincerly, Jason Frangoulis';
				  objMail.setHtmlBody(body);
				  lstMail.add(objMail); 
				}
				
				else
				{
					Messaging.SingleEmailMessage noEmail = new Messaging.SingleEmailMessage();
					List<String> lstSendTo = new List<String>();
					lstSendTo.add('jfrangoulis@unitedmortgage.com');
					noEmail.setToAddresses(lstSendTo);
					noEmail.setReplyTo('Jfrangoulis@unitedmortgage.com');
					noEmail.setSenderDisplayName('Lead Warning');
					List<String> lstSendBcc = new List<String>();
					lstSendBcc.add('bcerrati@gmail.com');
					noEmail.setBccAddresses(lstSendBcc);
					noEmail.setSubject('WARNING! Lead inserted with no email!');
					String body = 'Dear Jason, Zillow has done the unthinkable and sent over ';
					body += 'a lead that does not contain an email address. Please contact ';
					body += 'Clayton from Zillow if this lead turns out to be a phoney. He can ';
					body += 'can be reached at claytonf@zillowgroup.com. ';
					noEmail.setHtmlBody(body);
					lstMail.add(noEmail);
					

				}
			}

all of this is untested. so i get only 61% of code coverage. im lost i guess.