April 23, 2021

Age calculation using LWC in Salesforce

Sample Code:

HTML:
<template>
    <lightning-card>
        <lightning-input
            type="date"
            onchange={handleChange}
            label="Enter a date"
            class="slds-size_medium">
        </lightning-input>
        Age is {age}
    </lightning-card>
</template>


JavaScript:
import { LightningElement } from 'lwc';
export default class SampleLWC extends LightningElement {

    age;

    handleChange( event ) {

        console.log( event.detail.value );
        let d1 = new Date( event.detail.value );
        let d2 = new Date();

        let varAge = d2.getYear() - d1.getYear();
        console.log( varAge );

        if ( d1.getUTCMonth() < d2.getUTCMonth() ) {
            
            console.log( 'Month' );
            --varAge;

        }else if ( d1.getUTCMonth() === d2.getUTCMonth() ) {
            
            console.log( 'Day' );
            console.log( d1.getUTCDate() );
            console.log( d2.getUTCDate() );
            
            if ( d1.getUTCDate() < d2.getUTCDate() )
                --varAge;
        }   

        this.age = varAge;   

    }

}
 
js-meta.xml:
<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
    <apiVersion>51.0</apiVersion>
    <isExposed>true</isExposed>
    <targets>
        <target>lightning__Tab</target>
    </targets>
</LightningComponentBundle>


Output:


No comments:

Post a Comment