Start a conversation

Calculating with grids: dates

Following the basics described in Calculate with grid fields, the current article explains how to calculate with grids when the cells have been defined as "date".

Once again, the first step is to parse the JSON string. Although not necessary, it may be helpful to then put each date in a variable and then work with them in our calculation.  Here, we will work with the following example of a grid field named {gridField}:

We would like to know the amount of days that a patient has been hospitalized in the two visits to the hospital. Besides parsing the JSON string and declaring our variables for the dates, we will need to use the code in Calculate the difference between two dates.

First, we parse the grid field content:

var obj = JSON.parse('{gridField}');

* remember to replace '{gridField}' with the actual name of your grid variable

Since we have 4 dates, let's declare 4 variables, one for each of them:

var date1 = Object.values(obj[0])[0];
var date2 = Object.values(obj[0])[1];
var date3 = Object.values(obj[1])[0];
var date4 = Object.values(obj[1])[1];

Then, we calculate the difference between the admission and discharge dates for the first and the second hospitalization, separately:

var diffVisit1 = getDateDiff(date2,date1,'d')
var diffVisit2 = getDateDiff(date4,date3,'d')

Finally, we can show the result in a legible manner, for example:

"First visit: " + diffVisit1 + " days; " + "Second visit: " + diffVisit2 + " days"

In our study, all these pieces of code together will result in:

Choose files or drag and drop files
Was this article helpful?
  1. Castor Support Team

  2. Posted