C program to print digital clock with current time

CServer Side ProgrammingProgramming

In this section we will see how to make a digital clock using C. To work with time we can use the time.h header file. This header file has some function signatures that are used to handle date and time related issues.

The four important components of time.h is like below

  • size_t This size_t is basically the unsigned integral type. This is the result of sizeof().

  • clock_t This is used to store the processor time

  • time_t This is used to store calendar time

  • struct tm This is a structure. It helps to hold the entire date and time.

Example Code

#include <stdio.h>
#include <time.h>
int main() {
   time_t s, val = 1;
   struct tm* curr_time;
   s = time(NULL); //This will store the time in seconds
   curr_time = localtime(&s); //get the current time using localtime()
   function
      //Display in HH:mm:ss format
      printf("%02d:%02d:%02d", curr_time->tm_hour, curr_time->tm_min,
   curr_time->tm_sec);
}

Output

23:35:44
raja
Published on 15-Mar-2019 11:03:23
Advertisements