DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workkloads.

Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • Generics in Java and Their Implementation
  • TypeScript: Useful Features
  • Universal Implementation of BFS, DFS, Dijkstra, and A-Star Algorithms
  • Proper Java Exception Handling

Trending

  • GDPR Compliance With .NET: Securing Data the Right Way
  • My LLM Journey as a Software Engineer Exploring a New Domain
  • Kubeflow: Driving Scalable and Intelligent Machine Learning Systems
  • *You* Can Shape Trend Reports: Join DZone's Software Supply Chain Security Research
  1. DZone
  2. Data Engineering
  3. Data
  4. Adding Two Hours in DataWeave: Mule 4

Adding Two Hours in DataWeave: Mule 4

In this tutorial, follow an example case of a JSON array to learn the steps of implementing two hour values in DataWeave.

By 
$$anonymous$$ user avatar
$$anonymous$$
·
Feb. 10, 22 · Code Snippet
Likes (2)
Comment
Save
Tweet
Share
8.1K Views

Join the DZone community and get the full member experience.

Join For Free

Case: 

You are given a JSON array that will have all the employee's work details as an element. 

Example input in JSON : 

JSON
 
[
    {
        "Id": "870",
        "ProjectId": "705032",
        "ProjectName": "Out-Of-Office",
        "Hours": "04:00"
    },
    {
        "Id": "870",
        "ProjectId": "17427",
        "ProjectName": "ABC",
        "Hours": "08:00"
    },
    {
        "Id": "870",
        "ProjectId": "78185",
        "ProjectName": "XYZ",
        "Hours": "06:00"
    }
]

Expected output in JSON:

JSON
 
[
  {
    "TotalHours": "18.00"
  }
]

Implementation:

Let's analyze the input first.

  • The key is Hours and value is in the type of string.
  • We need to convert the string to Time, add those Time values, and return as Total Hour.

As we don't have any direct method to Add 2 Hours. We will be using our own Type HoursMinutes.

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

This HoursMinutes will have 2 elements as the hour and minute.

Steps:

  • Split based on a delimiter (in this case ":").
  • Convert the split strings to numbers.
  • Add minutes to minutes and hours to hours.
  • Concatenate both Hours and Minutes with a required delimiter. 

Look at the following DataWeave script:

JavaScript
 
%dw 2.0
output application/json

//Creating custom type
type HoursMinutes = {hour:Number, minute: Number}

//Function to convert String input to Custom type object
fun toHours(n: String): HoursMinutes = do {
    var split = n as String splitBy ":" //Change this if you have different delimiter 
    var hours = split[0] as Number
    var fromMin = floor(split[1] as Number / 60) // This is to make hours from minutes if minutes are greater than 60
    ---
    //output will be the custom type with hours and minute values
    {hour:floor(hours) + fromMin, minute:split[1] as Number mod 60}
  
}

//Function to add 2 Custom Type Objects
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}
}

//Function to form output in proper format (modify this if you want output differently)
fun toNumber(h: HoursMinutes) = (h.hour as String ++"."++ if (h.minute as String == "0") "00" else h.minute as String )  
---
[
    {
      //using reduce function with accumulator/lambda function
        "TotalHours": toNumber(payload reduce ((item, accumulator:HoursMinutes = {hour:0, minute:0}) -> accumulator add toHours(item.Hours))) 
    }
]

This Script will work even if hours are more than 24 and minutes are more than 60. It will automatically convert minutes to proper hours and process.

Reference is taken from this example.

JSON Strings Convert (command) JavaScript Data Types Element Analyze (imaging software) Data structure Implementation

Opinions expressed by DZone contributors are their own.

Related

  • Generics in Java and Their Implementation
  • TypeScript: Useful Features
  • Universal Implementation of BFS, DFS, Dijkstra, and A-Star Algorithms
  • Proper Java Exception Handling

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!