Code-based Actions: Working with dates
Within Flow, there is an advanced system in place that can detect, extract, convert, and format a date and time. This helps the end users to select a date and book an appointment.
Slot filling
The easiest way to work with dates and timings is using an Any text slot of the entity type Date.
Whenever a customer mentions text like today, next Saturday, or 12th of September the AI engine will transform this into a UTC date, relative to the timezone of the customer.
Date and time is relative
Flow works with a built-in timezone system. If the current date and time of a user in Amsterdam is 2 pm, 27th of August, the date and time are translated to a UTC date time format with the value 2019-08-27T12:00:00.000.
With UTC it is possible to transform a date to any local format. Since time is relative, tomorrow would represent different for a user in Japan, compared to users on the west coast of the US.
Formatting dates
If you want to format dates to a local format you need to use a code action.
To format dates and times, you need to use Moment.js and Moment Timezone package code actions:
// Convert a date to Dutch date format
moment(date).tz('Europe/Amsterdam').format('LLLL')
Use the following example code to format data and add it as a param:
async payload => {
const {
params
} = payload
if(Array.isArray(params.some_date)) {
// Format a date in Europe/Amsterdam format
return {
params: {
...payload.params,
formatted_date: \[{
value: moment(params.some_date[0].value).tz('Europe/Amsterdam').format('LLLL')
}]
}
}
}
}
The above code action converts a date and returns it as a new param.
Using a user's timezone offset
Within the payload of a Code Action, you can capture any user profile data, including timezone offset (if available).
The offset is the number of hours a user relative to UTC.
Use the timezone offset to convert a date to a local format with the following code:
async payload => {
const {
params,
user
} = payload
const {
profile
} = user
if(!Array.isArray(params.some_date)) {
// Skip if there is no date to format
return
}
// Dynamic timezone based on user timezone offset
const region = profile.timezone \< 0 ? `Etc/GMT${profile.timezone}` : `Etc/GMT+${profile.timezone || 0}`
return {
params: {
...payload.params,
formatted_date: \[{
value: moment(params.some_date[0].value).tz(region).format('LLLL')
}]
}
}
}
Read more
Updated about 1 year ago