+ Start a Discussion
Marc GauthierMarc Gauthier 

Adding a month to a date



I am  new to development and need some help.

I have a cutom object  "Payment__c" , this has all payment information related fields like card name, expire_date__c, etc .    I need to pull the fields values and add a month to the expire_date__c field. Below is my code,



Payment__c[] payment = [Select Name, expire_date__c FROM Payment__c];

String updatedexpire; 

for (Payment__c  temp : payment)


 updatedexpire=  temp.expire_date__c.Months(1);

System.debug ('the current value of updatedexpire==> '+updatedexpire );



The datetype of expire_date__c is Text(4)

When I execute  this piece of code in Anonymous  , it throws an error

"Method does not exist  or incorrect signature:[String].Months(Integer)"

Can anyone please help me.


Close! You want to use "addMonths(1)", see http://www.salesforce.com/us/developer/docs/apexcode/Content/apex_methods_system_date.htm


** EDIT ** 


Apologies, I misread your post. I assumed expire_date__c would be a date field, not a text field! How do you know what year it relates to? You should use a date field if you need to know that. If you're only concerned with the month then I would use a number field, unless you're using 'Jan', 'Feb' etc.. For credit cards I would always use a number for month and a number for year as it keeps things simple.


If you're using numbers just do something like:


integer month = Integer.valueOf(temp.expire_date__c) + 1;
month = (month == 12 ? 1 : month + 1);
updatedxpire = month;



how can u add the integer to a string value..as u are saying expire_date__c  is a text field .. and you are using months method to add the month ..but  this will happen if the field is of type date...


for example consider if that field is of type date then u can use


expire_date__c.addMonths(1);---> if this is date type only



if this is a string how can u identify the month component in that...if you can identify the index where exaclty month is then u can type cast the value and add '1' 



Can you please tell me in which format are you storing Date in field 'expire_date__c' by looking into live records, I can build up the logic for you.





I don't understand why you took data type TEXT(4) for expire_date__c. But it it was of date type then you could simply do following to get next expiry date

Date nextExpiryDate = expire_date__c.addMonths(1);

Now nextExpiryDate hold next month date.