Search code examples
dataweavemulesoftmule4

Find difference between two timeStamp using Dataweave


In my case, I have two time stamp requests and responses. I'm trying to calculate the millisecond difference between the two time stamps.

For example, if Time1 is "04:49:11.001" and Time2 is "04:49:21.001" then the difference is 10 seconds and 1000 milliseconds.

enter image description here

But it's not working correctly for Time1: "23:59:50.853" and Time2: "00:00:10.678". For this case, the date is updated to next date. I expect to get time difference value as 20000 millisecond.

but for the above code, I'm getting a negative value. enter image description here

My data weave code:

%dw 2.0
output application/json
var time1 = "23:59:50.001"
var time2 = "00:00:10.001"
---
(time2 - time1) as Number {"unit" : "milliseconds"}

Expert, please help me solve this logic.

Thanks in advance.


Solution

  • First the correct way to define a time value is using pipes: |23:59:50.001|. You are defining string variables and luckily DataWeave is auto converting correctly, but doing that may cause some issue in the future.

    What is happening here is that your input data is only time information. There are no dates involved so DataWeave has no way to know if the time is from this day or the next or in a year. It would not make sense to assume otherwise when working with time information only. So the result is to be expected. It is the number of milliseconds at 00:00:10.001 (starting from 00:00:00.000) minus the number of milliseconds of 23:59:50.001 (againg, counting from midnight). Obviously the later number is higher and the result negative.

    If you know that the times are from different dates then you need to use DataTime or LocalDateTime types for the calculation to have your expected results.

    Example:

    %dw 2.0
    output application/json
    var time1 = now() as Date ++ |23:59:50.001| 
    var time2 = now() as Date + |P1D| ++ |00:00:10.001| // adding a period of 1 day to today gives us tomorrow
    ---
    (time2 - time1) as Number {"unit" : "milliseconds"}
    

    Output:

    20000