Calculating the days between two dates


To insert today’s date or time into a field, prior to the forms submission, place the following script into the elements OnValidate event:

this.value = today();


this.value ="%H:%M");

Descriptive text can also be included with the function, for example:"today is %A, in %B")

this script will return: today is Tuesday, in May

Because this script has been entered against the element’s OnValidate event, it will not run until the form is submitted, and therefore, the date will not be visible to the user of the form.

Lua also supports the os.time function. This function can be used both with and without parameters. Without parameters, it returns a number of seconds, representing the current Operating System date and time. The returned value can be stored to a variable, or used in calculations against the current date. When used with parameters, the os.time function can return the number of seconds represented by a passed date/time.

●In the example below, lines 1 to 5 are used to create the variables used in the code that follows.
●Lines 7 to 9 split the date entered in the date element, StartDate into its year, month and date values, using the string.sub() function, storing them in the variables created above.
●Line 11 calls the os.time function, passing the year, month and day values to the os.time function as a Lua table, and stores the seconds value returned in the Startvariable. The first three parameters are required.Subsequent parameters, hours etc., are assumed 0 if not supplied.
●Line 13 takes the seconds value, calculated from the StartDate date element and subtracts it from the current operating system time. Then divides it by 60, to calculate the minutes difference, then divides it by 60 again, to calculate the hours difference.
●Line 14 places the number of hours calculated in the previous line, and places them in the Difference text box.

Whilst fewer lines could be used to achieve the same result, I have used this example to highlight the individual steps required to calculate the difference between two dates.

Was this article helpful?
0 out of 0 found this helpful

Need further help? Contact our Support Team