Salesforce Stack Exchange is a question and answer site for Salesforce administrators, implementation experts, developers and anybody in-between. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I feel that the following assertion should be true, but it is not:

DateTime testDate =;
System.assertEquals('"' + testDate.format('yyyy-MM-dd\'T\'hh:mm:ss.SSS\'Z\'' + '"'), JSON.serialize(testDate));

I get the following error:

16:38:28.966 (2966802000)|FATAL_ERROR|System.AssertException: Assertion Failed: Expected: "2014-04-03T04:38:27.988Z", Actual: "2014-04-03T20:38:27.988Z"

Update: when using formatGMT I still get the error:

DateTime testDate =;
System.assertEquals('"' + testDate.formatGMT('yyyy-MM-dd\'T\'hh:mm:ss.SSS\'Z\'' + '"'), JSON.serialize(testDate));

16:51:32.228 (2228010000)|FATAL_ERROR|System.AssertException: Assertion Failed: Expected: "2014-04-03T08:51:31.274Z", Actual: "2014-04-03T20:51:31.274Z"

share|improve this question
up vote 5 down vote accepted

I think the time wasn't in the correct format

DateTime testDate =; System.assertEquals('"' + testDate.formatGMT('yyyy-MM-dd\'T\'HH:mm:ss.SSS\'Z\'' + '"'), JSON.serialize(testDate));

share|improve this answer
Yes. that was it (facepalm).… hh == 12 hour hours. HH == 24 hour hours. – edgartheunready Apr 3 '14 at 21:17
sometimes another pair of eyes helps a lot :) – melmoussaoui Apr 3 '14 at 21:22

The DateTime.format() method converts the value to the time zone of the user who is running the test. The serializer is displaying the value as GMT.

A simple solution would be to use the DateTime.formatGMT() method in your test.

DateTime testDate =;
System.assertEquals('"' + testDate.formatGMT('yyyy-MM-dd\'T\'hh:mm:ss.SSS\'Z\'' + '"'), JSON.serialize(testDate));

Update: (The problem is in the format string as noted by @melmoussaoui - 'HH' vs 'hh')

DateTime testDate =;
String expectedValue = '"' + testDate.formatGMT('yyyy-MM-dd\'T\'HH:mm:ss.SSS\'Z\'' + '"');
String actualValue = JSON.serialize(testDate);
system.debug('Expected: ' + expectedValue);
system.debug('Actual:   ' + actualValue);
System.assertEquals(expectedValue, actualValue);

Debug output:

14:12:04:046 USER_DEBUG [4]|DEBUG|Expected: "2014-04-03T21:12:04.853Z"
14:12:04:046 USER_DEBUG [5]|DEBUG|Actual:   "2014-04-03T21:12:04.853Z"

Salesforce DateTime methods

share|improve this answer
I'm still getting an error. Does your code snippet work for you? – edgartheunready Apr 3 '14 at 20:54
@edgartheunready I've updated the answer and provided the debug output from my testing. – Mark Pond Apr 3 '14 at 21:17

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

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