简体   繁体   中英

DataWeave 2.0 get time difference as a period

I have DataWeave code that looks like below:

%dw 2.0
output application/java
var timezone = (now() >> "Pacific/Auckland") as String {format: "XXX"}
var t1 = '08:00:00.000' ++ timezone
var t2 = '21:00:00.000' ++ timezone
---
(|PT24H| - (t2-t1)) 

This results in a response in seconds as 39600 which is 11 hours. I want the response to be as |PT11H| rather than 39600. It works when we convert seconds to hours when dividing by 3600 to 11 hours but we need that to be like |PT11H| rather than 39600.

Above input t1 and t2 comes from config. we can't change the setup.

You can use seconds function of the dw::core::Periods module. It takes the number of seconds as Parameter and returns a Period.

%dw 2.0
import seconds from dw::core::Periods
output application/java

var timezone = (now() >> "Pacific/Auckland") as String {format: "XXX"}
var t1 = '08:00:00.000' ++ timezone
var t2 = '21:00:00.000' ++ timezone
---
seconds( |PT24H| - (t2 - t1) ) 

Another suggestion, since you are working on time periods and time differences the timezone does not really matter. You can reduce your code to below datawave

%dw 2.0
import seconds from dw::core::Periods
output application/java

var t1 = '08:00:00.000' as Time
var t2 = '21:00:00.000' as Time
---
seconds( |PT24H| - (t2 - t1) )  

The 'seconds' function is introduced in DataWeave version 2.4 and Mule Runtime 4.4 under the periodic module

Reference: seconds | MuleSoft Documentation https://docs.mulesoft.com/dataweave/2.4/dw-periods-functions-seconds

so if your Mule Runtime Version is lower than 4.4 then you have to go for dividing by 3600 as mentioned in the question itself.

Below is that solution too for developers who are using Mule Runtime Version lower than 4.4

First:

%dw 2.0
output application/java
var timezone = (now() >> "Pacific/Auckland") as String {format: "XXX"}
var t1 = '08:00:00.000' ++ timezone
var t2 = '21:00:00.000' ++ timezone
---
"|PT" ++ (|PT24H| - (t2-t1))/3600 ++ "H|"

Explanation: Since (|PT24H| - (t2-t1)) gives '39600' as the result which is in seconds, now to convert seconds to minutes you need to divide by 60, and then to convert minutes to hours you need to again divide by 60, So instead you can directly divide by (60 * 60 ie 3600) and get the hours.

as per suggestion in a comment if time is not in exact hours then we can use the below DataWeave script

Second:

%dw 2.0
output application/java
var timezone = (now() >> "Pacific/Auckland") as String {format: "XXX"}
var t1 = '08:00:00.000' ++ timezone
var t2 = '21:00:00.000' ++ timezone
---
"PT$(|PT24H| - (t2-t1))S" as Period

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM