Converting "2024-01-10T10:50:16.901-0500" timestamp to "2024-01-10T10:50:16.901Z" in DWL 2.0/Mule4

63 views Asked by At

I have a variable in Mule4 defined as receiptDateTime which has the following value:

output application/json
---
vars.receiptDateTime

The current output format of the vars.receiptDateTime is "2024-01-10T10:50:16.901-0500" but I need this to be converted to "2024-01-10T10:50:16.901Z" this format.

I have tried to do this in DWL playground and managed to get the conversion. Below is the DWL code:

output application/json

var h = payload.receiptDateTime as LocalDateTime {format: "yyyy-MM-dd'T'HH:mm:ss.SSSX"} as String {format: "yyyy-MM-dd'T'HH:mm:ss.SSS"}
var formattedDate = h ++ 'Z'

---
{
    "h": formattedDate
}

Is there any simpler way to get the conversion done using a function where I send the input vars to the function and get the formatted date back.

Expected OUTPUT format: "2024-01-10T09:57:33.523Z"

2

There are 2 answers

1
João Gervas On BEST ANSWER

If I understand what you need, you can just use function with a different output format.

The following code works in dataweave:

%dw 2.0
output application/json


fun formatDateTime(dt: String): String = 
    (dt as LocalDateTime {format: "yyyy-MM-dd'T'HH:mm:ss.SSSX"} as String {format: "yyyy-MM-dd'T'HH:mm:ss.SSS"}) ++ 'Z'
---
{
    "formattedDate": formatDateTime("2024-01-10T10:50:16.901-0500")
}

1
aled On

Do not use string concatenation for date time handling. That's a bad practice.

Instead use a pattern you can find in many pages and wrap your expression in a function instead or a variable to reuse it:

%dw 2.0
fun convertDateTimeToUtc(dt: DateTime)=
 dt as String {format: "yyyy-MM-dd'T'HH:mm:ss'Z'"}
---
...