Showing posts with label Code. Show all posts
Showing posts with label Code. Show all posts

Monday, March 24, 2014

Apex CASE Statement for Last Day of the Month

When using a CASE() statement to find the last day of the month in Apex code, I've seen a lot of developers -- both newbie & experienced coders alike -- test for every month, when really all that needs to be tested are the shorter months, defaulting to 31 for the rest. This is a better Apex CASE statement that's easier to read:

CASE(
    MONTH( TODAY() ), 
    2, IF( MOD( YEAR( TODAY() ), 4 ) = 0, 29, 28 ), 
    4, 30, 
    6, 30, 
    9, 30, 
    11, 30, 
    31 //default for months 1,3,5,7,8,10,12
)

This example is half as many lines, and much easier to read & understand. Since I don't think we'll be changing the Gregorian calendar any time soon, this construct should be safe.