add & subtract

Viewing 2 reply threads
  • Author
    Posts
  • January 12, 2023 at 2:44 PM #48615

    Glen Forister
    Participant

    After a couple hours, I got to this.

    function Age_Mo() {
    
    	// Replace with your own code
    
    	var today = record.getFieldValue('fld-04e68a0e6dac4e07b05701f6d441f646');
    	
    var purchased = record.getFieldValue('fld-68a95dfabc274628b44d6ee28cda71d8');
    
    var duration = [today] - [purchased]
    
    return duration
    }
    
    Age_Mo();

    All I get for a result ii “NaN”. Obviously, I’m missing something.

    What I want is the result is the difference between 2 dates in months.
    I also in the next field I want the result in years.

    • This topic was modified 1 year, 11 months ago by Brendan. Reason: Added back-ticks to format the code
    January 12, 2023 at 8:41 PM #48624

    Brendan
    Keymaster

    Hi Glen,

    You would not use the square brackets around [today] and [purchased].

    In JavaScript there’s a getMonth() function you can use on dates.

    So your formula would be:

    var duration = today.getMonth() - purchased.getMonth();

    FYI, NaN stands for Not a Number

    January 12, 2023 at 8:43 PM #48625

    Brendan
    Keymaster

    Actually there’s more to it because that doesn’t take into consideration the year.

    Try this function:

    function monthDiff(d1, d2) {
        var months;
        months = (d2.getFullYear() - d1.getFullYear()) * 12;
        months -= d1.getMonth();
        months += d2.getMonth();
        return months <= 0 ? 0 : months;
    }

    So you would call with this code:

    var duration = monthDiff(today, purchased);

    I just googled it, so I haven’t tested it.

    • This reply was modified 1 year, 11 months ago by Brendan.
Viewing 2 reply threads

You must be logged in to reply to this topic.