Current Time From Browser
The current time is:
We can get the current time with built- in JavaScript object Date
To get the time we have to create the Date object first simply like this
let currentDateTime = new Date();
As we created the date object
we can console.log to get the result
console.log(currentDateTime);
We get the result like this.
Sun Jun 16 2024 10:26:41 GMT+0600 (Bangladesh Standard Time)
we can separate the date in hour minute and seconds
let currentDateTime = new Date();
// Extract hours, minutes, and seconds from the current date and time
let currentHours = currentDateTime.getHours();
let currentMinutes = currentDateTime.getMinutes();
let currentSeconds = currentDateTime.getSeconds();
example code
// Step 1: Create a Date object
let currentDateTime = new Date();
// Step 2: Display the current date and time
console.log(currentDateTime);
// Step 3: Get the current hour, minute, and second
let currentHours = currentDateTime.getHours();
let currentMinutes = currentDateTime.getMinutes();
let currentSeconds = currentDateTime.getSeconds();
// Step 4: Display the hour, minute, and second
console.log('Current Hours: ' + currentHours);
console.log('Current Minutes: ' + currentMinutes);
console.log('Current Seconds: ' + currentSeconds);
A complete example where time gets from browser and update every second
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Real-Time Current Time Display Example</title>
<script>
// Function to retrieve and display the current time
function getCurrentTimeAndDisplay() {
// Create a new Date object to get the current date and time
let currentDateTime = new Date();
// Extract hours, minutes, and seconds from the current date and time
let currentHours = currentDateTime.getHours();
let currentMinutes = currentDateTime.getMinutes();
let currentSeconds = currentDateTime.getSeconds();
// Format hours, minutes, and seconds to ensure they are always two digits
currentHours = currentHours < 10 ? '0' + currentHours : currentHours;
currentMinutes = currentMinutes < 10 ? '0' + currentMinutes : currentMinutes;
currentSeconds = currentSeconds < 10 ? '0' + currentSeconds : currentSeconds;
// Construct the time string in HH:MM:SS format
let formattedTimeString = currentHours + ':' + currentMinutes + ':' + currentSeconds;
// Display the formatted time string in an HTML element with id "currentTimeDisplay"
document.getElementById('currentTimeDisplay').textContent = formattedTimeString;
}
// Update the displayed time every second (1000 milliseconds)
setInterval(getCurrentTimeAndDisplay, 1000);
</script>
</head>
<body>
<h1>Real-Time Current Time Display</h1>
<p>The current time is: <span id="currentTimeDisplay"></span></p>
</body>
</html>
You can Copy the example code and practice the code directly here