Validate LWC in different timezone

validate lwc in different time zone using console sensors
validate lwc in different time zone using console sensors

Scenario: You have a requirement to show different time zones, or to show meeting available times based on the user time zone. You created an LWC and now want to validate it from your own location.

How to validate LWC in different timezone using browser Sensors

This blog explains how to achieve that using Inspect > Sensors in your browser. Another benefit of using Sensors is that you can add your own required time zone: you just need to add the latitude and longitude of that time zone or location.

Intl.DateTimeFormat().resolvedOptions().timeZone gives you your current time zone, and you can convert it based on your requirement.

Find the video below, which explains all these details in short.

Read more about Intl.DateTimeFormat on MDN, and test your fundamentals with our LWC Basics Quiz.

validate lwc in different time zone using console sensors

LWC code to get the current time zone

//LWC JS
import { LightningElement } from 'lwc';

export default class GetTimeZone extends LightningElement {

    timeZone = 'IST';

    getTimeZone(timeZoneFromBrowser) { 
        const formatter = new Intl.DateTimeFormat('en-US', {
            timeZone: timeZoneFromBrowser,
            timeZoneName: 'shortGeneric',
        });

        const parts = formatter.formatToParts(new Date());
        const tzPart = parts.find((part) => part.type === 'timeZoneName');
        
        return tzPart ? tzPart.value : timeZoneFromBrowser;
    }

    handleClick() {
        this.timeZone = this.getTimeZone(Intl.DateTimeFormat().resolvedOptions().timeZone);
        console.log('Current Time Zone:', this.timeZone);
    }
}
// HTML
<template>
    <div class="slds-card">
        Your current time zone is: {timeZone}

        <lightning-button
            label="Get Time Zone"
            title="Get Time Zone"
            onclick={handleClick}
            class="slds-m-around_medium"
        ></lightning-button>
    </div>
</template>

Leave a Reply