Converting String to Date when you encounter Date /Month having a single digit for values less than 10 | Mule 4 | DataWeave 2.0
Sravan Lingam
MuleSoft Ambassador ???? Solution Architect ?? Mulesoft Meetup Leader ??All Certified MuleSoft Dev & Architect | 3 times MuleSoft All Star ??Award winner ???Owner of MuleSoft TechZone
Hello Muleys,
This is a short article on Converting a "String" to "Date" Type.
We know it's easy when we see proper String format.
Consider everything is in (MM/dd/yyyy) format throughout this article
eg: 06/09/2020 , 12/02/2020 , 01/28/2020
But sometimes we encounter a situation where we receive Date in String format from different sources like below:
eg: 6/9/2020 , 12/2/2020 , 1/28/2020
You can observe that the data is missing "0" when we have values like 6,2,1 instead of 06,02,01
In that Case our Syntax as Date {format : "MM/dd/yyyy" } FAILS , as it expects 2 digit number for date and month.
In that case, what's the solution?
Simple, use as Date {format : "M[01]/d[01]/yyyy"}
This will automatically append "0" if its value is < 10
eg:
%dw 2.0 output application/json var myDate = "9/23/2020" --- myDate as Date {format : "M[01]/d[01]/yyyy"} as String {format : "MM/dd/yyyy"}
Simple. So its always best practice to use this syntax so that it can take care of this situation
Happy Learning !
Yours
Sravan Lingam
Senior Consultant | Certified MCIA, MCPA
4 年Very useful
Integration Lead
4 年Sravan , would you mind sharing the source of where you found this format ? I recently ran into similar kind of challenge but couldn't find any info on this in official mule product documentation.
MuleSoft Integration Senior Developer
4 年Well said