8

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.

4
  • 1
    You mean so you can do something like DateTime yesterday = DateTime.yesterday();? I haven't seen anything in the DateTime methods or constructors that would directly support it as a literal. Agree that it would be useful though. May 7, 2013 at 23:03
  • 1
    Date.today().addDays(-1) for yesterday, Date.today().addDays(1) for tomorrow ? Or n for last / next n days? May 7, 2013 at 23:05
  • I edited the question to add an example and clarification. May 7, 2013 at 23:26
  • 2
    While we're at it, I'd love an Apex formula parser and criteria builder. But we probably are better off wishing for unicorns :)
    – jkraybill
    May 8, 2013 at 5:09

1 Answer 1

3

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.).

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .