Search code examples
muledataweavestring-to-datetime

Dataweave 2.0 - Cannot coerce String to LocalDateTime


I get a CSV file with data that I transform to application/java.

One of the fields (Creation_Date) is a DateTime field that I get as String because the output field is a string type.

Input field: Creation_Date (String) - Example: 2019-03-02 07:00:00.000

Output field: CreatedDate (String) - Example: 2019-03-02 08:00:00.000

I use that code in my Dataweave 2.0 transformation because I want to add one hour more to the input datetime:

CreatedDate: payload.Creation_date as LocalDateFormat {format: "yyyy-MM-dd HH:mm:ss+01:00"}

But it returns an error:

 Cannot coerce a String to a Localdatetime, caused by CreatedDate

Solution

  • To add or modify parts of the data such as adding hours you should convert to LocalDateTime and then use a Period to add a specific Period of time to the datetime. Also need to as milliseconds to format based on your expected input/output. Try this, but change pretendPayload to payload for your example:

    %dw 2.0
    output application/json
    var pretendPayload = {Creation_date: "2019-03-02 07:00:00.000"}
    
    type LocalDateFormat = LocalDateTime { format: "yyyy-MM-dd HH:mm:ss.SSS" }
    ---
    {
        CreatedDate: (pretendPayload.Creation_date as LocalDateFormat + |PT1H|) as String{format: "yyyy-MM-dd HH:mm:ss.SSS" }
    }
    

    Info on Period here: https://docs.mulesoft.com/mule-runtime/4.1/dataweave-types#dw_type_dates_period