Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
C program to print digital clock with current time
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 are 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.
Syntax
time_t time(time_t *timer); struct tm *localtime(const time_t *timer);
Example
Here's a complete C program to display the current time in digital clock format −
#include <stdio.h>
#include <time.h>
int main() {
time_t s;
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);
return 0;
}
Output
14:25:33
How It Works
- time(NULL) returns the current calendar time as seconds since January 1, 1970
- localtime() converts the time_t value to a struct tm representing local time
- %02d format specifier ensures two-digit display with leading zeros
- The tm_hour, tm_min, and tm_sec fields provide hour, minute, and second values
Conclusion
This simple digital clock program demonstrates how to use C's time functions to get and display the current time. The time.h library provides all necessary functions to work with system time in C programs.
