'Dataweave Date Formatting with Timezone

I'm trying to format a date to the following format, UTC with the Timezone Offset:

Expected: 2021-01-20T21:00:00-06:00

Actual: 2021-01-20T00:00:00-06:00

Code:

var arrivedAt = "2021-01-20T15:00:00"
var timezone = "America/Chicago"

var finalDateTime = (((arrivedAt as Date) as String {format: "yyyy-MM-dd'T'00:00:00"}) as LocalDateTime ++ (timezone as String)) 

I'm assuming it's due to the "00:00:00" in the format but when I try using "HH" or "hh" I'm receiivng errors.



Solution 1:[1]

The good news is that it's documented here https://docs.mulesoft.com/dataweave/2.3/dataweave-cookbook-change-time-zone

This example code assigns a timezone to the original date and then shift it to UTC

var arrivedAt = "2021-01-20T15:00:00"
var timezone = "America/Chicago"
var dateWithTimezone = (arrivedAt as LocalDateTime) ++ "America/Chicago"
// dateWithTimezone = "2021-01-20T15:00:00-06:00"
var dateOnUTC = dateWithTimezone >> "UTC"
// dateOnUTC = "2021-01-20T21:00:00Z"
--- 
dateOnUTC as String { format: "yyyy-MM-dd'T'HH:mm:ssXXX"}

NOTE: I'm not sure if the expected value is right on the question or if the example date is wrong.

Solution 2:[2]

It looks like you are using the incorrect data types and trying to do the date transformations as strings. That is highly unadvised. The errors are probably because a Date doesn't has a time neither a timezone.

One alternative is to treat the date time as a DateTime, to be able to use the timezone features:

%dw 2.0
output application/json
var arrivedAt = "2021-01-20T15:00:00"
var timezone = "America/Chicago"

var finalDateTime = (arrivedAt as DateTime >> timezone ) as String {format: "yyyy-MM-dd'T'HH:mm:ssZ"}
---
finalDateTime

Output

"2021-01-20T09:00:00-0600"

Actually the correct hour seems 9 instead of 21 as in your expected result. Maybe you did the timezone transformation the other way around?

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Community
Solution 2