How to calculate the number of days between two selected dates

Pau Sanchez Updated by Pau Sanchez

At times, when we work with dates, we might need to check difference between dates, it might be to check the length of a stay in an apartment or for how many days a customer wants to rent a tool. There are many other examples that you can think.

Natively Landbot doesn't support the difference of checking it, but with a little bit of Javascript, it is possible to pull it of:

In the following example we are going to select two dates, and based on the difference of day we will set a condition that will make the user move to one flow or the other.

Here is how the flow is going to look:

  1. We will ask the first date, and we will store it in the @dateone variable:

  1. we will ask now the second date, and we will save it in the @datetwo variable:

  1. Now to do the calculation we will add a JS Code block:

Here is the code (original code):

In Landbot 3

var dateone = "@{dateone}";
var datetwo = "@{datetwo}";

const oneDay = 24 * 60 * 60 * 1000; // hours*minutes*seconds*milliseconds
const firstDate = new Date(dateone);
const secondDate = new Date(datetwo);

const diffDays = Math.round(Math.abs((firstDate - secondDate) / oneDay));

console.log(diffDays)

this.setCustomData({difference:diffDays})

In Landbot 2

var dateone = "@{dateone}";
var datetwo = "@{datetwo}";

const oneDay = 24 * 60 * 60 * 1000; // hours*minutes*seconds*milliseconds
const firstDate = new Date(dateone);
const secondDate = new Date(datetwo);

const diffDays = Math.round(Math.abs((firstDate - secondDate) / oneDay));

console.log(diffDays)

Landbot.exec('landbot-custom-data', {'difference':diffDays})

  1. As you know, we need a user input to make the new variable created via Javascript (@difference) available to use in a Conditional block later. That is why we use a YES/NO block to force a user input. In this case we double check with the user, if the dates are correct

  1. Finally, we can set up a condition. Here we will check if the difference is greater than 6 days. It is important that when we select the variable @difference, as we need to create it, please select the format Number

How did we do?

Builder's keyboard shortcuts and mechanics! 🏗

How to access keys and values, in object variables

Contact