DateTime.day() returning inconsistent value when created from system.today()

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?

Answer

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());

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

Leave a Comment