Timer based on Date Time field using Lightning Web Component in Salesforce

Sample Code:

HTML:
<template>
    <lightning-card>
        Active Date/Time(GMT/UTC): {activeDateTime}<br/>
        {timer}
    </lightning-card>
</template>

JavaScript:
import { LightningElement, api, wire } from 'lwc';
import { getRecord, getFieldValue } from 'lightning/uiRecordApi';
import ACTIVE_SINCE_FIELD from '@salesforce/schema/Account.Active_Since__c';

export default class ActiveTimer extends LightningElement {

    @api recordId;
    account;
    error;
    activeDateTime;
    timer;
    setTimeInterval;
    totalMilliseconds;

    @wire( getRecord, { recordId: '$recordId', fields: [ ACTIVE_SINCE_FIELD ] } )
    wiredAccount( { error, data } ) {
        if ( data ) {

            this.account = data;
            console.log( 'Account is ' + JSON.stringify( this.account ) );
            console.log( 'Account Active_Since__c value is ' + this.account.fields.Active_Since__c.value );
            this.activeDateTime = this.account.fields.Active_Since__c.value;
            let currentDateTime = new Date();
            console.log( 'currentDateTime is ' + currentDateTime );
            console.log( 'currentDateTime in UTC is ' + currentDateTime.toISOString() );
            let diff = new Date( currentDateTime.toISOString() ) - new Date( this.activeDateTime );
            console.log( 'diff is ' + diff ); 
            this.totalMilliseconds = diff;
            this.setTimeInterval = setInterval( () => {
                let totalSeconds = parseInt( Math.floor( this.totalMilliseconds / 1000 ) );
                let totalMinutes = parseInt( Math.floor( totalSeconds / 60 ) );
                let totalHours = parseInt( Math.floor( totalMinutes / 60 ) );
                let days = parseInt( Math.floor( totalHours / 24 ) );
                let seconds = parseInt( totalSeconds % 60 );
                let minutes = parseInt( totalMinutes % 60 );
                let hours = parseInt( totalHours % 24 );
                let milliseconds = Math.floor( ( this.totalMilliseconds % ( 1000 ) ) );
                this.timer = days + " days " + hours + " hours " + minutes + " minutes " + seconds + " seconds " + milliseconds + " milliseconds "; 
                this.totalMilliseconds += 100;
            }, 100 );

        } else if ( error ) {

            console.log(  'Error: ' + JSON.stringify(error ) );

        }
    
    }
     

}

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

Output:


No comments:

Post a Comment