I am making a simple website that displays how long it has been since the last “red alert” in Israel. It uses this API: https://agg.rocketalert.live/api/v1/alerts/details. When testing with BrowserStack, I noticed that the time since the last alert is different depending on what time zone the user is in. How can I negate this and make it so that the time since last alert is the same for all users?
// Velo API Reference: https://www.wix.com/velo/reference/api-overview/introduction
// counter.js
// API endpoint URL
const apiUrl = 'https://agg.rocketalert.live/api/v1/alerts/details';
// Counter container
const counterContainer = $w('#counter')
// Function to fetch data from the API and update the counter
function updateCounter() {
fetch(apiUrl)
.then(response => {
if (!response.ok) {
throw new Error(`Network response was not ok: ${response.status} ${response.statusText}`);
}
return response.json();
})
.then(data => {
// Extract the payload array from the response
const payload = data.payload;
// Sort the dates in descending order
const sortedDates = payload.map(dateObj => dateObj.date).sort((a, b) => new Date(b) - new Date(a));
// Get the latest date
const latestDate = sortedDates[0];
// Get the alerts for the latest date
const alertsForLatestDate = payload.find(dateObj => dateObj.date === latestDate).alerts;
// Sort the alerts in ascending order by timestamp (since they are listed last)
const latestrecord = alertsForLatestDate.sort((a, b) => new Date(b.timeStamp) - new Date(a.timeStamp))[0];
const latesttimestamp =latestrecord.timeStamp;
const latestAlertTimestamp = new Date(latesttimestamp).getTime();
const utcOffsetInMilliseconds = -7 * 60 * 60 * 1000;
const adjustedTimestamp = latestAlertTimestamp + utcOffsetInMilliseconds;
const currentTime = Date.now();
const timeDifferenceMs = currentTime - adjustedTimestamp;
// Convert milliseconds to years, days, hours, minutes, and seconds
const years = Math.floor(timeDifferenceMs / (1000 * 60 * 60 * 24 * 365));
const days = Math.floor((timeDifferenceMs % (1000 * 60 * 60 * 24 * 365)) / (1000 * 60 * 60 * 24));
const hours = Math.floor((timeDifferenceMs % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
const minutes = Math.floor((timeDifferenceMs % (1000 * 60 * 60)) / (1000 * 60));
const seconds = Math.floor((timeDifferenceMs % (1000 * 60)) / 1000);
// Update the counter text
counterContainer.text = `${years} years, ${days} days, ${hours} hours, ${minutes} minutes, ${seconds} seconds`;
})
.catch(error => {
console.error('Error fetching data from the API:', error);
});
}
// Call the updateCounter function initially
updateCounter();
setInterval(updateCounter, 5000);
// Update the counter every second
I tried to add multiple UTC offsets, but they all did nothing to solve the issue of international users seeing different times.
For example, the current 7 hour offset works for my time zone but results in different times depending on where the user is located.