+ Start a Discussion
B TulasiB Tulasi 

I need to get Number of Years from olddate

Hi all, I have One custome field i.e. Hotel_Started_Date__C and i have another field i.e. Number_Of_Years__C. So, i need to get total years in between old date and Today date. For Example, if i enter "01/01/2000" in Hotel_Started_Date__C. It's need to calculate old date(01/01/2000) -  today date(09/09/2015) = 15 years. That 15 years nee to store in Number_Of_Years__C.

Note : Using Triggers

Thanks in advance
Thulasi
SaranSaran
Hi Tulasi,

Hope this below code will help you to solve your requirement.
 
trigger updateYear on Account (before insert,before update)
{
    for (Account acc : Trigger.New)
    {
    	if(acc.Hotel_Started_Date__C != null)
    	{
    		integer totalYear = today.year() - Hotel_Started_Date__C.year();
    		acc.Number_Of_Years__C = totalYear;
    	}
    }
}

I have written this for account object.

You can change it accordingly

Thanks!!
 
SaranSaran
Hi,

Small change in the code.

At line 7 instead of 
integer totalYear = today.year() - Hotel_Started_Date__C.year();
Use
integer totalYear = today.year() - acc.Hotel_Started_Date__C.year();

Thanks!
 
praveen jha 29praveen jha 29
Thanks Saran
B TulasiB Tulasi
Hi Saran,

I am getting this error...

 Error: Compile Error: Illegal assignment from Date to Integer at line 7 column 21

Code :
trigger yearInBusiness on New_Leads__c (before insert, before update) {

 for (New_Leads__c acc : Trigger.New)
    {
        if(acc.Business_Start_Date__c != null)
        {
            integer totalYear = system.today() - acc.Business_Start_Date__c.year();
            acc.Years__c = totalYear;
        }
    }
}
Here, Years_C field must want to take integer only. Why because, I need to store number in that. for exaple "15"
So, How to covert the value from date to integer.
 
    



 
SaranSaran
Hi,

Instead of 

 integer totalYear = system.today() - acc.Business_Start_Date__c.year();

use 


 integer totalYear = system.today().year() - acc.Business_Start_Date__c.year();

Hope this will work,

Thanks!