Danger: Date value can be assigned to a Datetime variable

Surprisingly in Apex it allows a Date value to be assigned to a Datetime variable without explicit conversion. See an example as follows:

Date d = Date.today();
Datetime dt = d;

Firstly, this would cause a timezone problem. Date d is created as today’s date. The debug log shows that Datetime dt is created based on the timezone of the organization the code is running. The time part of Date d is 00:00:00 GMT. So if the timezone of the organization is GMT-5, Datetime dt will have a 19:00:00 yesterday local time. When dt.day() is called, it returns yesterday’s day of the month. The correct way of converting Date to Datetime avoiding the timezone issue is to use the following statement:

Datetime dt = Datetime.newInstance(d.year(), d.month(), d.day());

Secondly, the fact that “a Date value can be assigned to a Datetime variable” in Apex makes an error to be noticed only at our latest managed package installation time. We had a global method in a class in our managed package (prefix: cve): cve.BusinessHoursUtil.addDays(Datetime, Integer). However a few code references in another managed package (prefix: cvestp) call this method passing in a date value and we have not noticed this for long time as it can compile. We recently added a overloaded method cve.BusinessHoursUtil.addDays(Date, Integer). Since this is the accurate method, the referencing code in cvestp should be now looking for the new method. However the cve version number for the referencing classes are at a much earlier version which does not have the new method. It still passes compilation and we can create our cvestp managed package. It gives out the following “method is not visible” error when the customer installs our cvestp managed package:

Dependent class is invalid and needs recompilation: (cvestp)
cvestp.IncompleteClaimTasks: line 77, column 28: Package Visibility:
Method is not visible: cve.BusinessHoursUtil.addDays(Date, Integer)

Published by Chun Wu

When nothing is certain, anything is possible.

Leave a comment

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: