Search code examples
muledataweavemule4

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.


Solution

  • 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) )