returning inconsistent value when created from

This came up on twitter from @britishboyindc:

Why does this return ‘Wed’?

Date myDt =;
DateTime myDtTime = (DateTime) myDt;

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.AssertException: Assertion Failed: Expected: 6, Actual: 7

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


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(, Time.newInstance(0,0,0,0));

Source : Link , Question Author : Daniel Ballinger , Answer Author : Vigneshwaran G

Leave a Comment