Hi community,
I’m building an Answers experience that returns a date-type field as a direct answer.
"games": {
"directAnswers": {
"fieldValues": {
"eligibleFields": [
"c_finalScore",
"c_datePlayed"
],
"predictionMode": "CLASSIFIER"
}
},
My question: How can I change how that raw date value is displayed? Instead of 2022-04-04
, I would prefer to show April 4, 2022
as that is much more user friendly.
I noticed that the allfields-standard
direct answer card has applies different formatting for different “cases” or field types. It looks like there isn’t a case for dates.
Could you advise how I can tweak a forked card and add a date formatter?
Thanks so much!
Max
Hey Max,
Yes, you can utilize a custom formatter to choose how your date should be displayed. Here is the general process using an example experience:
To start, I have events with a custom, date-type field called “Event Date”. Here is the default format of this date field in a direct answer:
First, use the “Override Theme” Jambo Command to fork the custom formatter file, found at static > js > formatters-custom.js.
Then, write and export your own custom date formatter in this file that manipulates the default value and gives it the desired format. My function looks like this:
// in formatters-custom.js
export function longDate(dateString) {
const parsedDateString = dateString + 'T00:00:00';
const date = new Date(parsedDateString);
const locale = "en";
const month = date.toLocaleString(locale, { month: 'long'});
const day = date.toLocaleString(locale, {day: 'numeric'});
const year = date.toLocaleString(locale, {year: 'numeric'});
return `${month} ${day}, ${year}`;
}
After creating this new formatter, you should use the “Add New Direct Answer Card” Jambo Command to create a custom direct answer card and select “allfields-standard” as the template.
In the component.js
file of this new custom card, add a case to the switch
statement that addresses date-type fields and applies the new custom formatter to the raw value:
switch (answer.fieldType) {
// ...all other cases
case 'date':
value = Formatter.longDate(answer.value);
break;
case 'single_line_text':
case 'multi_line_text':
default:
value = answer.value;
break;
}
Now, you simply have to update your universal/vertical config to reference your new card instead of allfields-standard
when surfacing direct answers for field values. Once you do this, that same date from the first screenshot will look like this:
Best,
DJ
1 Like
Thanks DJ! This worked perfectly.
Small caveat: I had to remove the + 'T00:00:00'
in my custom formatter since my date field only contains the month, day and year.