How to Convert 18 char Id to 15 char Id using substring in Apex trigger

All you need to do is convert the Id to a String and you can call substring(startIndex, endIndex) on it.

The following should work:

D.customfield__c = String.valueOf(acc.Id).substring(0, 15);

Following Spring '21 release, we can now use a dedicated function on the System.Id class called to15().

From the documentation:

Convert an 18-character Id value to a 15-character case-sensitive string. Use the to15() method in the System.Id class. This method uses the case-sensitivity checksum in the 18-character Id value to fix any mangled casing and returns a 15-character case-sensitive string.

Example:

    String Id_15_char = '0D5B000001DVM9t';
    String Id_18_char = '0D5B000001DVM9tkAh';
    ID testId = Id_18_char;
    System.assertEquals(testId.to15(),Id_15_char);

Tags:

Apex

Id

Trigger