Very often, it is necessary to calculate persons age (the most often in years) in a form field, based on the date value set in another field. This is very easy to do in skybow Solution Studio, skybow Rich Forms and modern skyForms, using the moment.js library.
Let's say, we have "birthday" date field, and "age" numeric field in a form. Your user has entered "birthday", and you need to calculate "age". Go to the calculated value of the "age" field, set the calculation method to "function" and do following:
// load the moment.js library from whereever you need it
var url = "https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.js";
var fileName = "momentjs";
var moduleCache = window.module;
var defineCache = window.define;
window.module = undefined;
window.define = undefined;
window.LoadSodByKey(fileName, null, true);
window.module = moduleCache;
window.define = defineCache;
//parse the "birthday" field with moment.js and get an integer representation of it
var dateInt = Date.parse(moment([[Birthday]]));
//now create a date object out the integer we got in the previous line
var dateObject = new Date(dateInt);
//now use moment.js to calculate difference between that day and now.
//We want "years" as calculation result (age in years)
//and the third parameter "false" tells us that we don't need fractions
var years = moment().diff(dateObject, 'years', false);
There you go! Please note, if you will use the moment.js on multiple places inside a form, it is better to load it in the form load actions, and use it later in the form or in the fields where needed.
Please sign in to leave a comment.