live ticking timer Salesforce


import { LightningElement, api } from 'lwc';
import getCreatedDate from '@salesforce/apex/SLAController.getCreatedDate';

export default class ElapsedTimer extends LightningElement {
    @api recordId;
    timeElapsed = '';
    interval;

    connectedCallback() {
        getCreatedDate({ recordId: this.recordId })
            .then(createdTime => {
                const createdDate = new Date(createdTime); // e.g., '2025-05-02T10:00:00.000Z'
                this.startCountUp(createdDate);
            })
            .catch(error => {
                console.error('Error fetching CreatedDate', error);
            });
    }

    startCountUp(createdDate) {
        this.updateElapsedTime(createdDate); // show immediately
        this.interval = setInterval(() => {
            this.updateElapsedTime(createdDate);
        }, 1000);
    }

    updateElapsedTime(createdDate) {
        const now = new Date();
        const diff = now - createdDate;

        if (diff <= 0) {
            this.timeElapsed = '00:00:00';
            return;
        }

        const hours = String(Math.floor(diff / (1000 * 60 * 60))).padStart(2, '0');
        const minutes = String(Math.floor((diff % (1000 * 60 * 60)) / (1000 * 60))).padStart(2, '0');
        const seconds = String(Math.floor((diff % (1000 * 60)) / 1000)).padStart(2, '0');

        this.timeElapsed = `${hours}:${minutes}:${seconds}`;
    }

    disconnectedCallback() {
        clearInterval(this.interval);
    }
}
========================================================================================

updateElapsedTime(createdDate) {
    const now = new Date();
    const diff = now.getTime() - createdDate.getTime();

    if (diff <= 0) {
        this.timeElapsed = '00h 00m 00s';
        return;
    }

    const totalSeconds = Math.floor(diff / 1000);

    const years = Math.floor(totalSeconds / (365 * 24 * 3600));
    const days = Math.floor((totalSeconds % (365 * 24 * 3600)) / (24 * 3600));
    const hours = Math.floor((totalSeconds % (24 * 3600)) / 3600);
    const minutes = Math.floor((totalSeconds % 3600) / 60);
    const seconds = totalSeconds % 60;

    this.timeElapsed =
        `${years}y ${days}d ` +
        `${String(hours).padStart(2, '0')}h ` +
        `${String(minutes).padStart(2, '0')}m ` +
        `${String(seconds).padStart(2, '0')}s`;
}
live ticking timer Salesforce live ticking timer Salesforce Reviewed by dasfrogpractice on 07:46 Rating: 5

No comments:

Theme images by mariusFM77. Powered by Blogger.
Youtube Channel Image
Dasfrog Subscribe To watch more Salesforce Training
Subscribe