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

Using DataWeave 2.0/Mule 4 to convert timestamp formats

When working with timestamps in DataWeave 2.0/Mule 4, you can easily convert one timestamp format to another. In this case, we want to convert the timestamp "2024-01-10T10:50:16.901-0500" to "2024-01-10T10:50:16.901Z". Here's how you can achieve this:

Using the format() function

The format() function in DataWeave allows you to convert a timestamp to a specific format. In this case, we want to convert the timestamp to the ISO 8601 format with the "Z" timezone indicator. Here's an example:

```

%dw 2.0

output application/json

var inputTimestamp = "2024-01-10T10:50:16.901-0500"

var outputTimestamp = inputTimestamp as DateTime {format: "yyyy-MM-dd'T'HH:mm:ss.SSSZ"} as String {format: "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"}

---

"inputTimestamp": inputTimestamp,

"outputTimestamp": outputTimestamp

```

In the above example, we first define the input timestamp as a string variable called "inputTimestamp". Then, we convert the input timestamp to a DateTime object using the specified format "yyyy-MM-dd'T'HH:mm:ss.SSSZ". Finally, we convert the DateTime object back to a string using the desired format "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'".

The output of the above DataWeave transformation will be:

```

"inputTimestamp": "2024-01-10T10:50:16.901-0500",

"outputTimestamp": "2024-01-10T10:50:16.901Z"

```

Using the replace() function

If you prefer a more concise approach, you can use the replace() function in DataWeave to replace the timezone offset "-0500" with "Z". Here's an example:

```

%dw 2.0

output application/json

var inputTimestamp = "2024-01-10T10:50:16.901-0500"

var outputTimestamp = inputTimestamp replace /-\d{4}$/ with "Z"

---

"inputTimestamp": inputTimestamp,

"outputTimestamp": outputTimestamp

```

In the above example, we use the replace() function with a regular expression pattern "/-\d{4}$/" to match the timezone offset at the end of the input timestamp. We then replace the matched timezone offset with "Z".

The output of the above DataWeave transformation will be the same as before:

```

"inputTimestamp": "2024-01-10T10:50:16.901-0500",

"outputTimestamp": "2024-01-10T10:50:16.901Z"

```

Conclusion

In DataWeave 2.0/Mule 4, you have multiple options to convert a timestamp from one format to another. You can use the format() function to specify the desired format or use the replace() function to replace specific parts of the timestamp. Both approaches will give you the desired output of "2024-01-10T10:50:16.901Z" for the given input timestamp "2024-01-10T10:50:16.901-0500".