Get time-zone & local time of your website visitors in Javascript
This is another follow-up of our previous post where we had discussed why it’s helpful to show the content on your website or app based on the user’s local time. It makes things more personal and user-friendly. Now, let’s get to the how-to part. In this article, we’re going to show you how to do it using simple JavaScript (if you need a code snippet in a different language, please contact us).
Prerequisites
To follow along, you’ll need:
- Basic understanding of HTML and JavaScript.
- Access to the ipapi.co API.
Step-by-Step Guide
Step 1: Set Up Your HTML
Start by creating a basic HTML structure with a <div>
element to display the local time.
<!DOCTYPE html>
<html>
<head>
<title>User's Local Time</title>
</head>
<body>
<div id="localTime"></div>
<script src="script.js"></script>
</body>
</html>
Step 2: Create Your JavaScript
Create a file named script.js
in the same directory as your HTML file. This is where the magic happens.
// Get the element to display the local time
const localTime = document.getElementById('localTime');
// Make a request to the ipapi.co API
fetch('https://ipapi.co/json/')
.then(response => response.json())
.then(data => {
const userTimezone = data.timezone;
// Get the current time in the user's timezone
const currentTime = new Date().toLocaleTimeString('en-US', { timeZone: userTimezone });
// Display the current local time
localTime.textContent = `User's local time: ${currentTime}`;
})
.catch(error => {
console.error('Error fetching user timezone:', error);
localTime.textContent = 'Failed to retrieve user timezone.';
});
Step 3: Test It Out
Open your HTML file in a web browser. You should see the local time of the user displayed on the page. Alternatively, please see the repl below (the local time displayed in the screenshot is not live) :
https://replit.com/@ipapi/Get-Timezone-and-Local-Time-in-Javascript
For any help / support, please don’t hesitate to contact us.