Saturday, October 11, 2025
HomeLanguagesJavascriptHow to make a digital clock in p5.js ?

How to make a digital clock in p5.js ?

The working of the clock is simple. The current hours, minutes and seconds is retrieved using the hour(), minute() and second() methods. The number returned is then padded with a “0” if it is less than 10 using the formatting function we will create. The AM or PM is determined by using the detected hours value. The whole time string is then displayed as a text using the text() method on the canvas.

Example:

Javascript




function setup() {
  
  // Create Canvas of given size
  createCanvas(480,480);
}
  
function draw() {
  
  // Set the background color
  background(0);
    
  // Set the strokeWeight to be thicker
  strokeWeight(4);
    
  // Get the current second, minute and hours
  // and assign them to res variables
  var sec = second();
  var min = minute();
  var hrs = hour();
    
  // Check for AM or PM based on the
  // hours and store it in a variable
  var mer = hrs < 12 ? "AM":"PM";
    
  // Format the time so that leading
  // 0's are added when needed
  sec = formatting(sec);
  min = formatting(min);
  hrs = formatting(hrs % 12);
    
  // Set the color of the background 
  fill(255);
    
  // Set the font size 
  textSize(48);
    
  // Set the text alignment in center
  // and display the result
  textAlign(CENTER, CENTER);
    
  // Display the time
  text(hrs + ":" + min + ":" + sec +
       " " + mer, width/2, height/2);
}
  
// This function pads the time
// so that 0's are shown 
// eg. 06,08,05 etc.
function formatting(num){
    
  // Convert to int and check 
  // if less than 10
  if(int(num) < 10) {
      
    // Return the padded number
    return "0" + num;
  }
    
  // Return the original number if
  // padding is not required
  return num;
}


Output:

Online Code editor:https://editor.p5js.org/

Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!
RELATED ARTICLES

Most Popular

Dominic
32350 POSTS0 COMMENTS
Milvus
87 POSTS0 COMMENTS
Nango Kala
6719 POSTS0 COMMENTS
Nicole Veronica
11881 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11941 POSTS0 COMMENTS
Shaida Kate Naidoo
6839 POSTS0 COMMENTS
Ted Musemwa
7101 POSTS0 COMMENTS
Thapelo Manthata
6794 POSTS0 COMMENTS
Umr Jansen
6794 POSTS0 COMMENTS