Calculate with Local Date

This sample code shows how to use the user's local date to do calculations.
In this specific example, the local date is used to calculated an age from a field containing the Birth date.

Sample Image

calculateage.gif

Sample Code

//Calculate age from birth date
(function() {
    'use strict';

    var BIRTHDATE = 'BirthDate'; //field code of a Date field
    var AGE = 'Age'; // field code of a number field
    var events = ['app.record.create.change.' + BIRTHDATE, 'app.record.edit.change.' + BIRTHDATE];

    kintone.events.on(events, function(event) {
        var record = event.record;

        function calculateAge(birthday) {
            function affixZero(int) {
                if (int < 10) { int = '0' + int; }
                return int;
            }
            var  birth = birthday.split('-');
            var _birth = parseInt(birth[0] + birth[1] + birth[2]);
            var  today = new Date();
            var _today = parseInt(today.getFullYear() + affixZero(today.getMonth() + 1) + affixZero(today.getDate()));
            return parseInt((_today - _birth) / 10000);
        }

        var age = calculateAge(record[BIRTHDATE].value);
        record[AGE].value = age;

        return event;
    });
}());

Notes

Make sure to match the Field code of your fields, with the Field code written in the code.
Note that the age is only calculated when a record is saved.

 

Refer to the Tutorial page, on how to add scripts to your app.

Was this article helpful?
0 out of 0 found this helpful
Comments
Please sign in to leave a comment.