Time formatting problem when using Moment.js and Dialogflow

Asked

Viewed 329 times

1

I have a problem typing some time in Dialogflow for my chatbot. I know the system works with AM and PM, but I tried to format the date with Moment.js (follow the code below), but it is not working. When placing an input of 9h, 10h, 11h or 12h it recognizes respectively as 21h, 22h, 23h and 00h. Any suggestions?

function consulta(agent) {
    let data = moment(agent.parameters.date).format('L');
    let tempo = moment(agent.parameters.time).tz('America/Recife').format('HH:mm');
    agent.add(`${data} às ${tempo}`);
}
  • 1

    I suggest [Edit] the question and put the value of agent.parameters.time, for cases that works and doesn’t work. So we can know better what might be happening (since now we can not know if it is a string, a Date, in which format comes, etc)

1 answer

1

According to the documentation on Moment.js formatting, the tokens HH and mm format, respectively, for the hour in 24 hours (between 00 and 23) and the minute (between 00 and 59).

So, if you want to format, for example, the time 3 hours and 8 minutes PM, using the pattern above, you will have:

"HH:mm" → 15:08

If you don’t want to format in the 24-hour template, you will need to use the tokens hh and mm, besides the A - to indicate AM or PM.

So, if you want to format the same time as before - 3 hours and 8 minutes PM - using this new pattern, you will have:

"hh:mm A" → 03:08 PM

So basically:

┌─────────┬─────────┬────────────────────────────┐
│  Tipo   │ Formato │          Exemplo           │
├─────────┼─────────┼────────────────────────────┤
│ Período │ A       │ AM (ou) PM                 │
│ Período │ a       │ am (ou) pm                 │
│ Horas   │ HH      │ 01, 02, ... 12, 13, ... 23 │
│ Horas   │ hh      │ 01, 02, ... 12, 01, ... 11 │
└─────────┴─────────┴────────────────────────────┘

Again, to learn more about these formats, see formatting documentation.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.