Extracting current age from birthdate in Dataweave 2.0

Author: Sanket Kangle

In a scenario where you have to populate the person’s exact age, and you have access to birthdate, you can do that now in a dataweave. One easy way one can think is just subtracting dates. When we subtract two dates, we get the time passed between two dates in hours, as illustrated in the example below.

To get the time elapsed in terms of years, months and dates, we need to use a function “between” from the “Periods” package. It is bundled in the dw::core

If we have the birthdate as input below


{   “birthDay”: “18-05-1990”}

Following script can be used to find the exact age today


%dw 2.0output application/jsonimport dw::core::Periods var today = now() as Date{ format: “dd-MM-yyyy”}var birthDay =  payload.birthDay as Date{ format: “dd-MM-yyyy”}var age = Periods::between(today, birthDay)—“age”: {   “years” : age.years,   “months”: age.months,   “days”: age.days   }

We will get following output as expected


{ “age”: {   “years”: 30,   “months”: 11,   “days”: 23 }}

Below is the screenshot of the Transform message component for the same.

I hope this was helpful.

Happy learning!

We use cookies on this site to enhance your user experience. For a complete overview of how we use cookies, please see our privacy policy.