Pages

Thursday, March 10, 2011

Comparing APEX Datetime instances

Something odd is happening with Datetime values in APEX automated tests.

At the start of an automated test case the current date and time is captured using:

  DateTime testStart = DateTime.now();

Then after a number of operations an Account is created. The automated test checks that the CreatedDate of the new Account (after insertion) is greater than when the automated test started.

System.assert(account.CreatedDate > testStart, 'New Account expected - Created Date['+account.CreatedDate+'] <= testStart date['+testStart+'].');

This test assertion fails with the CreatedDate and testStart having exactly the same value according to the assert message.

Converting the Datetimes to longs shows the testStart has more precision than the CreatedDate. It would appear that DateTimes stored in the database lose the millisecond precision.

System.assert(account.CreatedDate.getTime() > testStart.getTime(), 'New Account expected - Created Date['+account.CreatedDate.getTime()+'] < testStart date['+testStart.getTime()+'].');

1 comment:

  1. Thanks for the explanation. I also faced the same issue & was looking at the cause. I think milliseconds precision should also be stored in the database.

    ReplyDelete