Skip to content

Commit

Permalink
Update script.js
Browse files Browse the repository at this point in the history
  • Loading branch information
ms7ru authored Nov 30, 2024
1 parent a6e000b commit e30d66b
Showing 1 changed file with 50 additions and 30 deletions.
80 changes: 50 additions & 30 deletions clock/script.js
Original file line number Diff line number Diff line change
@@ -1,52 +1,72 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>World Time</title>
</head>
<body>
<div>
<p id="date"></p>
<p id="clock"></p>
</div>
<script>
let lastTime = null;

// Update the date
function updateDate() {
var now = new Date();
var year = now.getFullYear();
var month = now.toLocaleString('default', { month: 'short' });
var day = now.getDate();

// Format the date
var dateString = day.toString().padStart(2, '0') + '/' +
month + '/' +
year.toString();

// Update the date element
document.getElementById('date').textContent = dateString;
}
if (lastTime) {
const year = lastTime.getFullYear();
const month = lastTime.toLocaleString('default', { month: 'short' });
const day = lastTime.getDate();

// Update the date every second
setInterval(updateDate, 1000);

let lastTime = null;
// Format the date
const dateString = `${day.toString().padStart(2, '0')}/${month}/${year}`;

// Update the date element
document.getElementById('date').textContent = dateString;
}
}

async function updateTime() {
try {
// Fetch time data from the World Time API only once
const response = await fetch('https://worldtimeapi.org/api/timezone/Etc/UTC');
// Fetch time data from the API
const response = await fetch('https://api.api-ninjas.com/v1/worldtime?city=UTC', {
headers: { 'X-Api-Key': 'IqFWXtMcrzehyfH0YxCYjg==VBFfbPmaACUddPII' }
});

if (!response.ok) throw new Error('Failed to fetch time data');

const data = await response.json();

// Set the last known accurate time
// Parse the datetime from the API
lastTime = new Date(data.datetime);

// Update the clock immediately
// Update the date and clock immediately
updateDate();
displayTime();

// Start a local clock that updates every second
setInterval(displayTime, 1000);
setInterval(() => {
lastTime.setSeconds(lastTime.getSeconds() + 1);
updateDate();
displayTime();
}, 1000);

} catch (error) {
console.error('Error fetching time:', error);
}
}

function displayTime() {
if (lastTime) {
// Increment the time by 1 second
lastTime.setSeconds(lastTime.getSeconds() + 1);

// Display the time in 12-hour format with AM/PM
document.getElementById('clock').innerText = lastTime.toLocaleTimeString('en-US', { hour12: true });
}
}
if (lastTime) {
// Display the time in 12-hour format with AM/PM
document.getElementById('clock').textContent = lastTime.toLocaleTimeString('en-US', { hour12: true });
}
}

// Initialize the clock on page load
window.onload = updateTime;
</script>
</body>
</html>

0 comments on commit e30d66b

Please sign in to comment.