How to set a Date in an Apex class?

 

To set a date field to a fixed value in a Salesforce Apex class, you can use the newInstance(year, month, day) method from the Date class. The code looks like this:

Opportunity opp = new Opportunity();
opp.CloseDate = Date.newInstance(2022, 06, 09);

Another option that is especially useful in Apex test classes, is setting the date relative to today’s date. This helps overcoming issues with validation rules for future/past dates, etc. This can be done using System.today() for date-fields and System.now() for datetime-fields. In code it would look like this:

Opportunity opp = new Opportunity();
opp.CloseDate = System.today() + 3;

Instead of using “+ 3” you can also utilize the addDays(additionalDays) method.

Why did I write about this?

Even if I usually focus on Salesforce Marketing Cloud and this is related to the core Salesforce platform, it is a question that is still asked a lot, which I can also see based on the activity there is on a rather old answer on Salesforce StackExchange I wrote a couple of years ago about setting dates in apex test classes.

To make sure this information can be easily found for the readers of my blog as well, I thought I’d add a short post about it 🙂

Further Resources