Unix timestamp conversion to ISO 8601 in a Groovy script

I am new to Groovy and I'm engaged in a project where Groovy scripts are used. I need to convert a Unix timestamp to ISO 8601 format in a Groovy script. I couldn't find a straightforward and simple solution yet.

I have the following code now.

BigDecimal date = new BigDecimal('1641917151.819') //sample Unix timestamp
long date_int = (date.multiply(1000)).longValue()
def prov_time = new Date( date_int )
String iso_time = prov_time.format("MM/dd/yyyy'T'HH:mm:ss.SSS'Z'")
println(iso_time)

However, when I try this inside a Flowable Script Task, following error throws up;

problem evaluating script: javax.script.ScriptException: groovy.lang.MissingMethodException: No signature of method: java.util.Date.format() is applicable for argument types: (String) values: [MM/dd/yyyy'T'HH:mm:ss.SSS'Z'] Possible solutions: from(java.time.Instant), stream(), getAt(java.lang.String), parse(java.lang.String), print(java.lang.Object), print(java.io.PrintWriter)

My understanding is that there could be a version issue on Groovy, which doesn't support this method anymore. (Because when I try this on Groovy Console, I get the expected result). Also, I read that 'Date' type is pretty old and no longer used that much. Therefore, what should be the approach here?


Solution 1:

java.time.Instant has builders from epoch timestamps and its string representation is ISO 8601 at Zulu:

java.time.Instant.ofEpochMilli((1641917151.819 * 1000).longValue()).toString()
// -> 2022-01-11T16:05:51.819Z