Why does api.getElement(DATE).format produce an unexpected result?

Question

I need to pick a correct currency exchange rate using the BillingDate from transactional invoice lines and this code does not work as I would expect.

def billingDate = api.getElement('BillingDate').format('yyyy-MM-dd')

Let's assume a billingDate = "2019-09-30" (formatted date) which is retrieved by api.getElement('BillingDate'). When you apply format('yyyy-MM-dd') on top of this value, the following string is returned: "yyyy-MM-dd". When you do not apply format('yyyy-MM-dd'), the following string is returned: "2019-09-30". Why is this so?

Answer

This code snippet mixes up the Groovy default method for java.util.Date and the method for java.lang.String. Since the data type of api.getElement("MyDateElement") is java.lang.String, the latter is dispatched.

So it is required that you parse the value into a Java Date first, using the following code:

api.parseDate('yyyy-MM-dd',api.getElement('BillingDate')) // returns a java Date

If the source format matches the target format, you often do not need to do any conversion at all.

Found an issue in documentation? Write to us.