How do I format the date in dataweave?

Advertisements

I want to format the date that is stored in variable called "value"

output application/json
var value = "202206"
---
{
    "date": value as String {format: "yyyyMM"} as String {format: "yyyy-MM-01"},
    "month": value as String {format: "yyyyMM"} as String {format: "MMMM"},
}

I need the output like this

{
"date": "2022-06-01",
"month": "June"
}

I know it can be done, but I cant seem to figure it out.

>Solution :

You need to get a "Date" object for formatting it as a String. Currently your value = "202206" is a String, and when you do value as String{format:.. you are just coercing / type casting a String as String. Therefore at this point dataweave does not know what is the year and date in the String 202206

So you will first need to convert your value as Date and then to String.

%dw 2.0
output application/json
var value = "202206"
var valueAsDate = (value ++ "01") as Date {format: "yyyyMMdd"} // You can not have a date without a day. So we need to add 01 to make the value 20220601
---
{
    "date": valueAsDate as String {format: "yyyy-MM-dd"},
    "month": valueAsDate as String {format: "MMMM"}
}

Leave a Reply Cancel reply