I am working on building a rules processor and have a text (string) field in a custom metadata type that I would like to store a formula in (i.e. datetime.now()) and then convert to the correct field format within apex. Is this something that can be done? I know that I can use something like below to parse an actual datetime string:

(field.ValueType__c == 'Date/Time'){
DateTime dt = DateTime.parse(field.ValueType__c);    
o.put(field.APIFieldName__c, dt); 

In the custom metadata I am storing Value, ValueType, and IsFormula, but am having trouble figuring out how to actually set the formula for the datetime variable. Thanks.

1 Answer 1


There's no way to "evaluate apex" on-the-fly (at least, not in the traditional sense), but you can get some limited support for formulas via apex:outputText, or you can perform a callout to execute anonymous (requires administrative permissions). The caveat for using apex:outputText is that you must be in a Visualforce context.

Here's an example that should work in a Visualforce context:

Component.Apex.OutputText c = new Component.Apex.OutputText();
c.expressions.value = '{!NOW()}';
DateTime dt = DateTime.valueOf(c.value);

However, as stated, it will not work in other contexts, like triggers, batchable, etc.

For now, you might want to vote on this idea.


You must log in to answer this question.

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