14

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?

1
  • 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. Apr 7, 2016 at 22:35

1 Answer 1

17

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());
1
  • 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. Apr 8, 2016 at 0:17

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .