首页 > 解决方案 > MULE 4:DATAWEAVE 2.0:如何获取 Dataweave 2.0 中两个 Time 实例之间的小时数差异?

问题描述

我的要求是获取文件的年龄。我使用 And 来获取文件创建时间#[attributes.creationTime] ,为了获取年龄,我与当前时间做了一个差异。

<set-variable value="#[now() - attributes.creationTime]" doc:name="File Duration" doc:id="a7c594b0-3a03-4054-a65a-d32dc08c06e1" variableName="fileAge"/>

这将 fileAge 设置为:PT-3H-23M-1.577259S

根据 Mule 4 文档,https://docs.mulesoft.com/mule-runtime/4.3/dataweave-types#duration-coercion

我试图通过这样做来获得年龄:

案例 1:vars.fileAge as Number {unit: "hours"} 和案例 2:vars.fileAge.hours

在情况 1 中,我收到错误:

org.mule.runtime.core.api.expression.ExpressionRuntimeException: "Cannot coerce Object { encoding: UTF-8, mediaType: application/java; charset=UTF-8, mimeType: application/java, raw: org.mule.weave.v2.module.pojo.reader.JavaBeanObjectValue$JavaBeanObjectSeq@23e1079b, class: java.time.Duration } ({nano: 422741000 as Number {class: "java.lang.Integer"},units: ["SECONDS" as ...) to Number

1| vars.fileAge as Number {unit: "hours"} 
   ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Trace:
  at main (line: 1, column: 1)" evaluating expression: "vars.fileAge as Number {unit: "hours"} ".

在案例 2 中,我得到空值。

有人可以帮帮我吗?

但是我遇到了一个错误

标签: dataweavemule4

解决方案


更改您的变量,以便生成 JSON 作为输出:

output application/json --- now() - attributes.creationTime

编写 DW 表达式时的默认输出是application/java. 如果你注意你的变量的类型设置为java的,如果你想执行类型转换java.time.Duration,它应该是DW的。切换到 JSON 允许 DW 为您的数据创建类型。Periodas Number {units: "hours"}Period

我敢打赌,如果我足够努力,我将能够弄清楚如何(或者我可以在哪里Duration投入并投入Period. 如果我以后有更多时间,我会研究它,或者其他人可以提供更好的答案。


推荐阅读