13

This came up on twitter from @britishboyindc:

Why does this return 'Wed'?

Date myDt = system.today();
DateTime myDtTime = (DateTime) myDt;
system.debug(myDtTime.format('E'));

For a user with the Pacific Standard Time TimeZone this is currently returning 'Wed' when it is Thursday.

I've also found the following assertion fails:

DateTime myDateTime = System.today();
System.assertEquals(myDateTime.day(), System.today().day());

System.AssertException: Assertion Failed: Expected: 6, Actual: 7

Why does assigning the DateTime to a variable change the value?

  • I suspect the issue is that System.today() returns a Date, not a DateTime. There is a conversion going on with the variable assignment that is losing the timezone details. – Daniel Ballinger Apr 7 '16 at 22:35
15

The problem was with initializing the DateTime variable by casting from a Date. As the Date had no Timezone information, the resulting DateTime was created at UTC+0. For Pacific Standard Time at the point of testing this put the current DateTime on the previous day.

Instead of directly casting the Date to a DateTime, the DateTime.newInstance(date, time) method should be used to construct the DateTime in the local time zone.

E.g. This will pass the assertion.

DateTime myDateTime = DateTime.newInstance(System.today(), Time.newInstance(0,0,0,0));
System.assertEquals(myDateTime.day(), System.today().day());
| improve this answer | |
  • 3
    I had this problem in a test class. It would pass tests if run before 8PM EST, but would fail if run between 8 and midnight, because I was calculating the day differently in two places. – Jeremy Nottingham Apr 8 '16 at 0:17

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.