Date formatting in DataWeave 2.0
We often encounter scenarios to convert dates from one format to another, and I find the date formatting a massive task in itself. Date conversion becomes essential in a state of affairs where there is a need to sync two databases/systems. It’s not an easy task since most databases/systems have their specific formats. Maybe the client wants a date in some particular format; hence, the responsibility to convert from one format to another falls upon Mule or, say, falls upon us, MuleSoft developers. We’ll explore on conveniently change the date formatting in DataWeave.
Let’s start simple and understand the native date types in DataWeave Format.
- Date: Date represented in yyyy-MM-dd format. E.g: 2020-10-17
- DateTime: Conjunction of Date and time in yyyy-MM-ddTHH:mm:ss format with timezone. E.g: 2020-10-17T23:57:59+05:30
- LocalDateTime: Conjunction of Date and time in yyyy-MM-ddTHH:mm:ss format without timezone.E.g: 2020-10-17T23:57:59
- LocalTime: Time in the current timezone.E.g: 23:57:59
- Timezone: Time relative to GMT. Must start with a + or – . E.g: +05:30
- Period: Represents an amount of time in following form P[n]Y[n]M[n]DT[n]H[n]M[n]S. It consists of two parts – Date period, the part before T and Duration, the part after T
Below is the DataWeave script to check the native date types in DataWeave:
Below is the Output for the script above:
To get the current time of the system, Dataweave offers now() function.
Printing now() will output:
The details like day, month, year etc., are facilitated by now() function.
Below is the output for the script above:
DataWeave can help us attain dates in different formats than what now() returns. Please note that the below script is just an example of the different date formats and doesn’t encompass all the possible scenarios.
Here, we saw a few examples of formatting system dates and dates received as part of payload into different formats and how to extract information from dates.
*There can be many more scenarios for date conversions other than the one in this MuleSoft technical guide.