Instanceof for Apex Date and DateTime

Just spent some time chasing a unit test error where the date returned in some code was a day out. The code being tested was:

SObject sob = ...
Object o = sob.get(f);
Date d;
if (o instanceof DateTime) {
    d = ((DateTime) o).date();
} else if (o instanceof Date) {
    d = (Date) o;
}

In the end this unit test demonstrated the cause of the problem:

@IsTest
private class InstanceofTest {
    @IsTest
    static void date() {
        Object o = Date.today();
        System.assertEquals(true, o instanceof Date);
        System.assertEquals(true, o instanceof DateTime);
    }
    @IsTest
    static void dateTime() {
        Object o = DateTime.now();
        System.assertEquals(false, o instanceof Date);
        System.assertEquals(true, o instanceof DateTime);
    }
}

So a Date is a DateTime (as well as a Date) and that was pushing the code through some unwanted timezone offsetting.

A fix is:

SObject sob = ...
Object o = sob.get(f);
Date d;
if (o instanceof Date) {
    d = (Date) o;
} else if (o instanceof DateTime) {
    d = ((DateTime) o).date();
}

and a lesson learned is to be paranoid about the type system in Apex.

Advertisements

2 thoughts on “Instanceof for Apex Date and DateTime

  1. Hi Keith,

    You did this on the appexchange awhile ago: http://salesforce.stackexchange.com/questions/30730/trigger-update-case-field-based-on-feeditem

    I was wondering if you would be able to help me with a small task.

    We migrated to the community builder and went from tracking SLA’s on case comment related list to using case feed. Except inherently, you can’t initially track SLA’s on case feed.

    I was thinking to do the first internal case feed comment could count towards the SLA through our entitlement and escalation process (which is set up). When I tried doing this in process builder I couldn’t do a formula because there was no case feed field to pull in.

    Can you assist with this?

    Thanks,

Leave a Reply

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 )

Google+ photo

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

Connecting to %s