Learner
Learner

Reputation: 159

Adding two hours and minutes in dataweave 2.0

I need to sum the below hours and minutes.

[{"hours": 20.50},{"hours":30.55}]

expecting result should be: [{"hours" : 51.45}]

How do you think I can add the hours in dataweave 2.0 if not help me in java.

Upvotes: 0

Views: 785

Answers (2)

Padma
Padma

Reputation: 1

Can also try this way :

%dw 2.0
output application/json
import leftPad from dw::core::Strings
    var cumulativeHours = payload reduce(item, acc = {}) -> do{
        var hours = (item.hours  splitBy ":" ) [0] as Number 
        var minutes = (item.hours splitBy ":") [1] as Number
        var sumOfhours = acc.sumOfhours default 0
        var sumOfMinutes = acc.sumOfMinutes default 0
    ---
    {
        sumOfhours : sumOfhours + hours,
        sumOfMinutes: sumOfMinutes + minutes,
        hoursFromMinutes : floor((sumOfMinutes + minutes)/60),
        minutes : (sumOfMinutes + minutes) mod 60
        
    }
}

---
hours: "$(cumulativeHours.sumOfhours + 
       cumulativeHours.hoursFromMinutes):$(cumulativeHours.minutes)"

Upvotes: 0

Christian Chibana
Christian Chibana

Reputation: 568

I'm not sure if we can take advantage of the Time Types that include DW to solve this, so I wrote a solution that uses a custom type HoursMinutes that let the hours to be more than 24, parse a Number to HoursMinutes, add them, and finally transform it again to Number.

Maybe I over complicate it... hahah

%dw 2.0
output application/json

type HoursMinutes = {hour:Number, minute: Number}

fun toHours(n: Number): HoursMinutes = do {
    var split = n as String splitBy "."
    var fromMin = floor(split[1] as Number / 60)
    ---
    {hour:floor(n) + fromMin, minute:split[1] as Number mod 60}
}

fun add(hour1:HoursMinutes, hour2: HoursMinutes): HoursMinutes = do {
    var fromMin = floor((hour1.minute + hour2.minute) / 60)
    ---
    {hour: hour1.hour + hour2.hour + fromMin, minute: (hour1.minute + hour2.minute) mod 60}
}

fun toNumber(h: HoursMinutes) = (h.hour as String ++"."++ h.minute as String) as Number
---
[
    {
        "hours": toNumber(payload reduce ((item, accumulator:HoursMinutes = {hour:0, minute:0}) -> accumulator add toHours(item.hours)))
    }
]

Upvotes: 3

Related Questions