Tuesday, September 10, 2013

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 all that's really needed is to test for 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 since I don't think we'll be changing the Gregorian calendar any time soon, it should be safe.

No comments:

Post a Comment