15

I have written a test class in which I just want to set one date field. How can I achieve this? I am not able to set the value using the following code:

Account acc=new Account();
acc.effectiveDate__c= '09.12.2016';

4 Answers 4

29

You can do this using Apex' Date class:

acc.effectiveDate__c = Date.newInstance(2016, 12, 9);

For more information check out the documentation: Apex Developer Guide - Date Class

1
  • Gosh I wish you could use date literals like in SOQL for setting fields in Apex 😫 Couldn't find an Idea in the IdeaExchange yet. acc.EffectiveDate__c = 2016-09-12; Sep 23, 2021 at 0:21
7

Another option is using system.today() (or system.now() if it's datetime field):

acc.effectiveDate__c = System.today() + 5;
1
  • This is what I personally try to use in my own unit tests. I find that not hard-coding a specific date helps in writing better date-centric logic.
    – Derek F
    Mar 7, 2017 at 13:02
0

Another option is using system.today().addDays(10)

acc.effectiveDate__c = System.today().addDays(10);

-2

a.SLAExpirationDate__c = date.parse('4/17/2020');

You need to use date.parse to execute the code

2
  • It's not necessary to instantiate dates in this specific manner.
    – Adrian Larson
    Apr 16, 2020 at 16:53
  • Not only is it unnecessary, it is a very poor idea, because Date parsing depends on the running user's locale.
    – David Reed
    Apr 20, 2020 at 14:28

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.