Updating Digital Clock Reading to Always Match Current Time

Hello. This is my first post so please correct me if my formatting is awful.

I am trying to have a simple date and time print onto the monitor. I am able to print the values using their corresponding functions from processing, however I would like them to update an match the actual time on each iteration of draw(). Right now they will match the time I initialized the program and remain static.

int M = month();      //month
int D = day();        //day
int Y = year();       //year
int Hr = hour();      //hour          
int Min = minute();   //minute
int Sec = second();   //second 
PFont dateAndTime;

void setup() {
  size(400, 400);
  background(0);
  dateAndTime = createFont("Monospaced", 20);
}

void draw() {
  background(0);
  displayDate();
  displayTime();
  textAlign(CENTER);
}

//-----------------------------------------------------------
void displayDate() {
  String Ms = str(M);
  String Ds = str(D);
  String Ys = str(Y);
  String MDY = Ms + "/" + Ds+ "/" + Ys;

  textFont(dateAndTime);
  text(MDY, 200, 180);
}

//------------------------------------------------------------
void displayTime() {
  String Hrs = str(Hr);
  String Mins = str(Min);
  if (Mins.length() < 2) {
    Mins = "0" + Mins;
  }
  String Secs = str(Sec);
  if (Secs.length() < 2) {
    Secs = "0" + Secs;
  }
  String HMS = Hrs + ":" + Mins + ":" + Secs;
  textFont(dateAndTime);
  text(HMS, 200, 200);
}

Any ideas on how to do this?

1 Like

Well this is embarrassing but at least it is fixed. I had declared the variables that store the values of minutes, seconds, etc. OUTSIDE of draw() so they weren’t constantly updating. I moved them inside now and it works.

I don’t know how to delete a forum post so hopefully this will help someone in the future.

1 Like

Glad you figured it out!

Just to be clear – you can also use those functions (eg seconds()) directly in displayTime() and displayDate() (which are called by draw) without saving them to variables first – no local or global variables needed if all you want is display.

Hello!

Can you show what you did in the code to make it work? I am very new to coding XD

Hello,

Processing has resources (tutorials, references, examples, etc.) here:
processing.org

References:

This should give you some insight after you read the references:

// Global variable declarations
// Set before setup() and draw()
int sec = second();

// Runs once
void setup() 
  {
  size(200, 200);
  textAlign(CENTER, CENTER);
  textSize(48);
  }

// Loop that repeats 60 frames per second (default)
void draw() 
  {
  background(0);
  //sec = second();  // Try this as part of code! It is a commented now
  text(sec, 100, 100);
  }