[SalesForce] Can you use SOQL Date Literals in Apex

Date Literals are really helpful in SOQL queries. There are times in Apex where it would be really helpful to be able to use the literals or some sort of easy equivalent (not in a SOQL query). Is there any easy way to do this or is the best solution to try and hack to together using Date functions?

An example – let's say I want to know if a particular date was in the last quarter – in SOQL I could do something like:

SELECT Id FROM Opportunity WHERE closedate = LAST_QUARTER

I'd like to be able to do something similar in Apex:

if(o.closedate == LAST_QUARTER){
  //do something
}

It can be tough to figure this out, especially with people using different quarters, locales, etc. The SOQL date literals do a great job and I'd like to be able to reuse that logic in Apex. Yes, I could rewrite it using date functions but it's not a trivial task, especially when you take in to account the idea of it being part of a package and it having to adjust for different customers.

It's mostly useful when trying to find time frames that are harder to define, like weeks and quarters.

I realize something like my example doesn't exist, but I didn't know if there was something similar out there that SFDC has to make these things easier.

Best Answer

There is no way to do this by standard. If you do write the code to do this though I'd encourage you to share it as a utility class on GitHub. If you do so and it proves useful it may well end up being incorporated in platform like ApexLang was.

All the new String methods in the previous release came from open sourced code like this, and once it's part of the platform it no longer contributes excessively to governor limits (i.e. you'd get one statement count increment for calling the method, not one for each line of the method.).