-1

I am trying to convert date which is in string to date format, am receiving error. Please help me in resolving.

Input-

{
    "Date" : "220907"
}

Code

output application/java
---
payload.Date as String {format: "YYMMDD"} as Date{format: "YYMMDD"}

`````

Error-

Cannot coerce String (220907) to Date, caused by: Text '220907' could not be parsed: Unable to convert 220907 to Date.

4| payload.Date as String {format: "YYMMDD"} as Date{format: "YYMMDD"} ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Trace: at main::main (line: 4, column: 1)

Avinash
  • 19
  • 6
  • The coercion to String from String is useless, since it is already a String. – aled Nov 01 '22 at 02:00
  • Not knowing Mule, is that a `java.util.Date`? I recommend you don’t use it since it is poorly designed and long outdated. Use `LocalDate` from [java.time, the modern Java date and time API](https://docs.oracle.com/javase/tutorial/datetime/index.html). Sorry, I cannot tell you how conversion in Mule happens then. – Ole V.V. Nov 01 '22 at 08:31
  • That recommendation is appropriate to Java but not applicable to DataWeave. The implementation of DataWeave uses Java infrastructure but it is not visible directly to users. Formatting characters are the same though. – aled Nov 01 '22 at 18:42

1 Answers1

1

The input has already a string. You need to parse it into a Date first. You need to use the right format characters for year and day. DataWeave uses the same format as Java does. It is lowercase 'y' for year and lowercase 'd' for day of month.

%dw 2.0
output application/java
---
payload.Date as Date {format: "yyMMdd"}
aled
  • 21,330
  • 3
  • 27
  • 34