Use cases are rare but displaying the live time on a webpage is a neat feature, perhaps for a dashboard or panel would it suit best.
There is no need for Jquery just pure vanilla JavaScript and some defined HTML spans.
Base code is 12 hour time with AM/PM and the date says the day (name), month and day (number). These of course can be changed.
HTML elements to display the live time and date:
<span class="hours_mins_secs"></span> <span class="am_pm"></span> <br> <span class="date"></span>
And the Javascript code is:
function liveTime() {
var dateInfo = new Date();
var hr,
_min = (dateInfo.getMinutes() < 10) ? "0" + dateInfo.getMinutes() : dateInfo.getMinutes(), //If less than 10 add 0 onto front 1 -> 01
sec = (dateInfo.getSeconds() < 10) ? "0" + dateInfo.getSeconds() : dateInfo.getSeconds(),
am_pm = (dateInfo.getHours() >= 12) ? "PM" : "AM"; //Decide if AM or PM
if (dateInfo.getHours() == 0) { //24hr to 12 hour calculations
hr = 12;
} else if (dateInfo.getHours() > 12) {
hr = dateInfo.getHours() - 12;
} else {
hr = dateInfo.getHours();
}
var currentTime = hr + ":" + _min + ":" + sec;
document.getElementsByClassName("hours_mins_secs")[0].innerHTML = currentTime; //hh:mm:ss element
document.getElementsByClassName("am_pm")[0].innerHTML = am_pm; //AM or PM element
var day_name = [
"Sunday",
"Monday",
"Tuesday",
"Wednesday",
"Thursday",
"Friday",
"Saturday"
],
month = [
"January",
"February",
"March",
"April",
"May",
"June",
"July",
"August",
"September",
"October",
"November",
"December"
],
day = dateInfo.getDate();
var currentDate = day_name[dateInfo.getDay()] + ", " + month[dateInfo.getMonth()] + " " + day; //replaces int with string. Day = 2 is Tuesday
document.getElementsByClassName("date")[0].innerHTML = currentDate; //Date element
};
liveTime();
setInterval(function() {
liveTime()
}, 1000); //1 second updates
A drained and empty Kennington reservoir images from a drone in early July 2024. The…
Merrimu Reservoir from drone. Click images to view larger.
Using FTP and PHP to get an array of file details such as size and…
Creating and using Laravel form requests to create cleaner code, separation and reusability for your…
Improving the default Laravel login and register views in such a simple manner but making…
Laravel validation for checking if a field value exists in the database. The validation rule…