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';

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


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

acc.effectiveDate__c = System.today() + 5;
  • 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 '17 at 13:02

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

You need to use date.parse to execute the code

  • It's not necessary to instantiate dates in this specific manner. – Adrian Larson Apr 16 '20 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 '20 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.