Hear from Salesforce leaders on how to create and deploy Agentforce agents.
Contact Us 1-800-596-4880

Format Dates and Times

You can use DataWeave to change the format of date and time input. Before you begin, note that 2.x versions of DataWeave are used by Mule 4 apps. For DataWeave in Mule 3 apps, refer to DataWeave version 1.2 examples. For other DataWeave versions, you can use the version selector in the DataWeave table of contents.

Change Date and Time Formats

You can combine formatting characters, such as MM and dd, to write supported date and time formats. The example uses the as operator to write the dates and times as a string.

Transform
%dw 2.0
output application/json
---
{
  formattedDate: |2020-10-01T23:57:59| as String {format: "uuuu-MM-dd"},
  formattedTime: |2020-10-01T23:57:59| as String {format: "KK:mm:ss a"},
  formattedDateTime: |2020-10-01T23:57:59| as String {format: "KK:mm:ss a, MMMM dd, uuuu"}
}
dataweave
Output
{
  "formattedDate": "2020-10-01",
  "formattedTime": "11:57:59 PM",
  "formattedDateTime": "11:57:59 PM, October 01, 2020"
}
json

Create a Custom Date Format as a DataWeave Type

For multiple, similar conversions in your script, you can define a custom type as a directive in the header and set each date to that type. Names of DataWeave type are case-sensitive.

DataWeave Script
%dw 2.0
output application/json
type Mydate = String { format: "uuuu/MM/dd" }
---
{
  formattedDate1: |2019-10-01T23:57:59| as Mydate,
  formattedDate2: |2020-07-06T08:53:15| as Mydate
}
dataweave
Output
{
  "formattedDate1": "2019/10/01",
  "formattedDate2": "2020/07/06"
}
json

Use Date and Time Formatting Characters

DataWeave supports the use of formatting characters, such as the u (for the year), M, and d in the date format uuuu-MM-dd. These characters are based on the Java 8 java.time.format package.

The following example formats the output of the now DataWeave function to show supported letters:

DataWeave Script

Notice the use of the syntax to format the date or time.

Output