How to Add Days, Months, and Years to Date field in Salesforce Apex

Recently, while working as a Salesforce developer, I received a task to add days, months, and years to a date field. The requirement was to automate the user subscription trial extension.

When new customers sign up for a product trial, they receive a 14-day trial period by default. However, the sales team offers a 7-day extension to customers upon request. We had to update the customer’s trial end date by adding seven extra days to their current trial end date.

In this Salesforce tutorial, I will explain how to add days, months, and years to a Date field in Salesforce Apex using various methods.

Add Days to a Date Field in Salesforce Apex

In Salesforce Apex, we can use the addDays() method to add days to the date field.

Now, execute the code below in the Salesforce Apex anonymous window to add days to a date field in Salesforce Apex.

Date today = Date.today(); 
Date myDate = today; 
Date futureDate = myDate.addDays(10); 

System.debug('Today\'s Date: ' + today);
System.debug('Future Date: ' + futureDate);

In the above code, “Date futureDate = myDate.addDays(10)” will add ten days to the date value that is today’s date in the code.

Now, in the execution log window, we will see that the number of dates is added to the date value for which we used the addDays() method.

Add days to a date field in Salesforce Apex

This way, we can add the number of days to a date field in Salesforce Apex using the addDays() method.

Add Months to a Date Field in Salesforce Apex

In Salesforce Apex, we can use the Date.addMonths() method to add months to a date field. This method uses an integer as an argument, representing the number of months to add in the date field.

Now, execute the code below in the Apex anonymous window to add months to a date field.

Date today = Date.today();
Date futureDate = today.addMonths(3);

System.debug('Today\'s Date: ' + today);
System.debug('Future Date (after adding 3 months): ' + futureDate);

In the above code, Date.today() will get today’s date, and today.addMonths(3) will add three months to the date value.

Now, in the execution log window, you will see today’s date and the date value with the added three months in the debug.

Add months to a date field in Salesforce Apex

This way, we can add the number of months to the date field in Salesforce Apex using the Date.addMonths() method.

Add Months to a Specific Date in Salesforce Apex

We can use the Date.addMonths() to add months to a specific date field like, 23/10/2024.

Execute the code below in the Salesforce Apex anonymous window