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

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

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

Related

  • Implementing NetSuite Add Records Operation With MuleSoft - Part II
  • Implementing MUnit And MUnit Matchers With MuleSoft
  • API-Led Example: MuleSoft
  • Tired of Messy Code? Master the Art of Writing Clean Codebases

Trending

  • A Deep Dive Into Firmware Over the Air for IoT Devices
  • The Full-Stack Developer's Blind Spot: Why Data Cleansing Shouldn't Be an Afterthought
  • Performing and Managing Incremental Backups Using pg_basebackup in PostgreSQL 17
  • Concourse CI/CD Pipeline: Webhook Triggers
  1. DZone
  2. Data Engineering
  3. Data
  4. DataWeave: Play With Dates (Part 1)

DataWeave: Play With Dates (Part 1)

This blog gives insights into the very basic date operations or functions that a developer would be using on a regular basis.

By 
Muralidhar Gumma user avatar
Muralidhar Gumma
·
Jan. 04, 24 · Code Snippet
Likes (1)
Comment
Save
Tweet
Share
6.4K Views

Join the DZone community and get the full member experience.

Join For Free

DataWeave is a very powerful language provided by MuleSoft to transform data. It is the primary language of MuleSoft for data transformation and an expression language for components and connectors configuration.

This blog gives very good insights into the very basic date operations or functions that a developer would be using on a regular basis.

  1. Find the number of days between two dates
  2. Find if a given date or date time is a leap year
  3. Add days to the current date or any provided date
  4. Subtract days from the current date or any provided date
  5. Add and subtract years to the current date or any provided date
  6. Change a Time Zone
  7. Find the latest DateTime, Date, Time from a given list of DateTimes

1. Find the Number of Days Between Two Dates

The daysBetween DataWeave function can be used to find the number of days between any two dates. This can be applied in scenarios where you need to find the number of days between the start and end dates of a membership/contract. The data type of the output generated by this function is "Number."

This function accepts two mandatory parameters, and the type of parameters should always be either in date or date time.

This function does not accept null or empty strings. It gives an error if any values are provided as input parameters other than date or date times.

Input

JSON
 
{
    "membership": {
        "startDate": "27-05-2023",
        "endDate": "27-06-2025"
    }
}


DataWeave Expression

JSON
 
%dw 2.0
output application/json
---
{
"numberOfDays" : daysBetween((payload.membership.startDate as Date {format:"dd-MM-yyyy"}), payload.membership.endDate as Date {format:"dd-MM-yyyy"})
}


Output

JSON
 
{
  "numberOfDays": 762
}


2. Find Out if a Given Date or Datetime Is a Leap Year

The isLeapYear DataWeave function can used to find if any given date or datetime is a leap year. This function gives true if a date or datetime is a leap year; otherwise, it returns false. This can be applied in scenarios where a company plans to provide any discounts or offers for the membership fee if the membership is being created in a leap year. The data type of the output generated by this function is "Boolean."

This function accepts a mandatory parameter, and the type of the parameter should always be either in date or date time.

This function does not accept null or empty strings. It gives an error if any values are provided as input parameters other than date or date times.

DataWeave Expression

JSON
 
%dw 2.0
output application/json
---
{
    "leapYearTest1" : isLeapYear(now()),
    "leapYearTest2" : isLeapYear("27-06-2025" as Date {format:"dd-MM-yyyy"}),
    "leapYearTest2" : isLeapYear("2023-09-23T13:59:35.340539Z")
}


Output

JSON
 
{
  "leapYearTest1": true,
  "leapYearTest2": false,
  "leapYearTest2": false
}


3. Add Days to the Current Date or Any Provided Date

The DataWeave examples below show multiple ways to add days to a date and DateTime. All the dataweave examples added below are for dataweave 2.x, which is only available in Mule 4.x.

The examples below use:

  • as function to coerce a String to Period type
  • P<date>T<time> for the Period data type, which provides designators for years, months, days, hours, minutes, and seconds
    For example, |P2Y9M1D| refers to a period of two years, nine months, and one day, and |PT5H4M3S| indicates a time period of five hours, four minutes, and three seconds.

DataWeave Expression

JSON
 
%dw 2.0
output application/json
var numberOfDays = 3
---
{
  oneDayAfter: |2023-10-01T23:57:59Z| + |P1D|,
  threeDaysAfter: |2023-10-01T23:57:59Z| + ("P$(numberOfDays)D" as Period),
  a: |2020-10-01| + |P1D|,
  b: |P1D| + |2020-10-01|,
  c: now() + |P1D|
}


4. Subtract Days From the Current Date or Any Provided Date

The DataWeave examples below show multiple ways to subtract days from a date and DateTime. All the dataweave examples added below are for dataweave 2.x, which is only available in Mule 4.x.

The examples below use:

  • as function to coerce a String to Period type
  • P<date>T<time> for the Period data type, which provides designators for years, months, days, hours, minutes, and seconds
    For example, |P2Y9M1D| refers to a period of two years, nine months, and one day, and |PT5H4M3S| indicates a time period of five hours, four minutes, and three seconds.

DataWeave Expression

JSON
 
%dw 2.0
output application/json
var numberOfDays = 3
---
{
  oneDayBefore: |2019-10-01T23:57:59Z| - |P1D|,
  threeDaysBefore: |2019-10-01T23:57:59Z| - ("P$(numberOfDays)D" as Period),
  a: |2024-01-06| - |P1D|,
  b: |P1D| - |2023-10-01|,
  c: |2023-10-01T23:57:59Z| - |P1D|,
  d: |2023-10-01T23:57:59| - |P1D|,
  e: |2019-10-01| - |2018-09-23|,
  f: |2019-10-01T23:57:59Z| - |2018-10-01T23:57:59Z|,
  g: |2019-10-01T23:57:59| - |2018-10-01T23:57:59|,
  h: now() - |P1D|
}


Output

JSON
 
{
  "oneDayBefore": "2019-09-30T23:57:59Z",
  "threeDaysBefore": "2019-09-28T23:57:59Z",
  "a": "2024-01-05",
  "b": "2023-09-30",
  "c": "2023-09-30T23:57:59Z",
  "d": "2023-09-30T23:57:59",
  "e": "PT8952H",
  "f": "PT8760H",
  "g": "PT8760H",
  "h": "2024-01-04T08:23:13.448587Z"
}


5. Add and Subtract Years To Current Date or Any Provided Date

The DataWeave examples below show multiple ways to add and subtract years from a date and DateTime. All the dataweave examples added below are for dataweave 2.x, which is only available in Mule 4.x.

The examples below use:

  • as function to coerce a String to Period type
  • P<date>T<time> for the Period data type, which provides designators for years, months, days, hours, minutes, and seconds
    For example, |P2Y9M1D| refers to a period of two years, nine months, and one day, and |PT5H4M3S| indicates a time period of five hours, four minutes, and three seconds.

DataWeave Expression

JSON
 
%dw 2.0
output application/json
var numberOfYears = 3
---
{
  oneYearBefore: |2023-10-01T23:57:59Z| - |P1Y|,
  threeYearsBefore: |2023-10-01T23:57:59Z| - ("P$(numberOfYears)Y" as Period),
  a: |2023-12-01| - |P2Y|,
  b: |P2Y| - |2019-10-01|,
  c: |2023-10-01T23:57:59Z| - |P1Y|,
  d: |2023-10-01T23:57:59Z| + |P1Y|,
  e: |2023-10-01T23:57:59| - |P1Y|,
  f: |2019-10-01| - |2018-09-23|,
  g: |2019-10-01T23:57:59Z| - |2018-10-01T23:57:59Z|,
  h: |2019-10-01T23:57:59| - |2018-10-01T23:57:59|,
  i: now() - |P1Y|,
  j: now() + |P1Y|
}


Output

JSON
 
{
  "oneYearBefore": "2022-10-01T23:57:59Z",
  "threeYearsBefore": "2020-10-01T23:57:59Z",
  "a": "2021-12-01",
  "b": "2017-10-01",
  "c": "2022-10-01T23:57:59Z",
  "d": "2024-10-01T23:57:59Z",
  "e": "2022-10-01T23:57:59",
  "f": "PT8952H",
  "g": "PT8760H",
  "h": "PT8760H",
  "i": "2023-01-05T08:28:34.739095Z",
  "j": "2025-01-05T08:28:34.739098Z"
}


6. Change a Time Zone

The DataWeave example below presents a way to change the time zone in MuleSoft using DataWeave.

The example uses >> operator and a time zone ID to change the time zone. It also uses the formatting characters uuuu-MM-dd'T'HH:mm:ss.SSS to modify the format. The uuuu characters represent the year. 

The expression below uses a custom function, "format," which takes a parameter of type "DateTime." 

DataWeave Expression

JSON
 
%dw 2.0
output application/json
fun format(d: DateTime) = d as String {format: "yyyy-MM-dd'T'HH:mm:ss.SSS"}
---
{
    CreatedDateTime: format(|2019-02-13T13:23:00.120Z| >> "CET"),
}


Output

JSON
 
{
  "CreatedDateTime": "2019-02-13T14:23:00.120"
}


7. Find the Latest DateTime, Date, Time From a Given List of DateTimes

The DataWeave example below presents a way to find the latest DateTime, Date, and Time from inputs defined in the variables myDateTime1 and myDateTime2. It also shows that the function returns null on an empty array.

DataWeave Expression

JSON
 
%dw 2.0
var myDateTime1 = "2017-10-01T22:57:59-03:00"
var myDateTime2 = "2018-10-01T23:57:59-03:00"
output application/json
---
{
  myMaxBy: {
    byDateTime: [ myDateTime1, myDateTime2 ] maxBy ((item) -> item),
    byDate: [ myDateTime1 as Date, myDateTime2 as Date ] maxBy ((item) -> item),
    byTime: [ myDateTime1 as Time, myDateTime2 as Time ] maxBy ((item) -> item),
    emptyArray: [] maxBy ((item) -> item)
  }
}


Output

JSON
 
{
  "myMaxBy": {
    "byDateTime": "2018-10-01T23:57:59-03:00",
    "byDate": "2018-10-01",
    "byTime": "23:57:59-03:00",
    "emptyArray": null
  }
}


Conclusion

This blog has covered various operations that can be performed on Years, DateTimes, Dates, and Times in Mulesoft using Dataweave through a series of Datweave examples and Datweave scripts.

Data transformation MuleSoft Strings Data Types

Opinions expressed by DZone contributors are their own.

Related

  • Implementing NetSuite Add Records Operation With MuleSoft - Part II
  • Implementing MUnit And MUnit Matchers With MuleSoft
  • API-Led Example: MuleSoft
  • Tired of Messy Code? Master the Art of Writing Clean Codebases

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!