Search code examples
dialogflow-essql-date-functions

In DialogFlow when date is displayed it come with YYYY-MM-DD HH-MM-SS format how to convert to DD-MM-YYYY format?


The response given by the bot for date given by user for example 20th july is 2021-07-20T12:00:00+05:30. How to convert this to 2021-07-20?


Solution

  • I think using the webhook we can do that. Here is some code reference.

    Prerequisites:

    • Create new intent and add a event like 'dateConverter'
    • enter image description here
    • Add response in newly created intent with Converted date: $date (Here in date we have formatted date)
    • Enable the webhook for the intent for which date is being captured.
    • Configured webhook in fulfillment section.

    Here is the sample Node code. const express = require('express'); const fetch = require('node-fetch');

    const app = express()
    const port = process.env.PORT || 3000;
    app.listen(port, () => {
        console.log(`Starting server at ${port}`);
    });
    
    app.use(express.json())
    
    app.post('/date-converter', async (req, res) => {
    console.log("Dialogflow: Received a POST request");
    if (!req.body) return res.sendStatus(400)
    if (req.body.queryResult.parameters.hasOwnProperty('given-date')){
      let date = req.body.queryResult.parameters['given-date']
      let dateFormatter = date.split('T')[0].split("-").reverse().join("-");
      let responseObj = {
       "followupEventInput": {
         "name": "dateConverter",
         "parameters": {
          "date": dateFormatter
        }
       },
      "source": ""
      }
      return res.json(responseObj)
      }
      })
    

    So when your main intent in which user has provided the date intent trigger then it'll call the webhook and convert the date format. After converting the date format it'll internally call the intent which has a event dateConverter with the specific parameter that we have defined in the webhook response.(Here we have define the date).

    I think by using this we can convert the date from the YYYY-MM-DD HH-MM-SS to DD-MM-YYYY or whatever format you want.

    NOTE: For this sample user captured date should be stored in the given-date parameter. If you have different name then you need to change the name in the above code snippet.

    Result: enter image description here

    Let me know if you face any issue.