Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pauljacobson/f388945b61be9bd86acb06a99f475dbc to your computer and use it in GitHub Desktop.
Save pauljacobson/f388945b61be9bd86acb06a99f475dbc to your computer and use it in GitHub Desktop.
Sharing code for a JavaScript script that displays a real-time date-time field that updates automatically, without a browser refresh.
// The purpose of this block is to list the month names which will correspond with the
// corresponding numerical value of the particular month that is other derived from
// the getDate() method.
Date.prototype.monthName = function() {
const monthsOfYear = ['January', 'February', 'March', 'April', 'May', 'June',
'July', 'August', 'September', 'October', 'November', 'December'];
return monthsOfYear[this.getMonth()];
}
// As with the previous block, this block states the days of the week so the script
// can match the named days of the week to corresponding numerical values.
Date.prototype.dayName = function() {
const daysOfWeek = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday',
'Friday', 'Saturday'];
return daysOfWeek[this.getDay()];
}
function realtimeClock() {
const now = new Date(),
today = now.dayName(),
year = now.getFullYear(),
month = now.monthName(),
day = now.getDate(),
secs = ('0' + now.getSeconds()).slice(-2),
mins = ('0' + now.getMinutes()).slice(-2),
hours = now.getHours(),
container = document.querySelector('.clock');
container.innerHTML = `Today is ${today}, ${day} ${month} ${year}.
The current time is ${hours}:${mins}:${secs}`;
requestAnimationFrame(realtimeClock);
};
requestAnimationFrame(realtimeClock);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment