在dataweave中将时区从未定义更改为utc

问题描述

我有一个简单的日期/时间字符串(欧洲当地夏令时/冬令时),我想转换为 UTC。

我收到的日期是这样的

{"message": "2021-05-01 15:39"}

但是像这样使用 LocalDateTime

(payload.message as LocalDateTime  {format: "yyyy-MM-dd HH:mm"}  >> "UTC")

将提供“2021-05-01T15:49:00Z” - 虽然正确(分别是我想要的)应该是“2021-05-01T13 :49:00Z"。

解决方法

一种解决方案是手动添加时区:

%dw 2.0
output application/json
var value={"message": "2021-05-01 15:39"}
---
(value.message ++ " CET") as DateTime  {format: "yyyy-MM-dd HH:mm zz"}  >> "UTC"

输出:

"2021-05-01T13:39:00Z"
,

您无法将其直接解析为 DateTime(带有时间和时区的日期),因为您没有 TimeZone .. 所以,手动添加时区然后解析它,这样您就可以转换时区到 UTC。

(("$(payload.message) +02:00") as DateTime { format: "yyyy-MM-dd HH:mm ZZZZZ" }) >> "UTC"

输出:

"2021-05-01T13:39:00Z"

编辑:

如果我们假设 mule 应用程序的时区与通过的日期时间的时区相匹配,并且我们想动态添加它,我们可以这样做:

%dw 2.0
output application/json
fun currentUTCOffset() = now() as String { format: "ZZZ" }
---
(("$(payload.message) $(currentUTCOffset())") as DateTime { format: "yyyy-MM-dd HH:mm ZZZ" }) >> "UTC"

这就是为什么人们在传输时间时包含有关时区的信息如此重要的原因……如果不包含时区信息就很难解析,尤其是在每年更改时区两次的地方。