C Program to Make a Digital Clock Using C Graphics

Write a program in C to make a digital clock using graphics.h header file

In this program, we will make a digital clock that print current Day, Month, Year and Date on screen inside a rectangular box. We will use below mentioned graphics functions in this program. Here, we are using time function of time.h header file to get the current epoch time(epoch time is number of seconds since 1 January 1970, UTC). We convert epoch time to string representing the localtime in “www mmm dd hh:mm:ss yyyy” format, where www is the weekday, mmm is the month in letters, dd is the day of the month, hh:mm:ss is the time, and yyyy is the year. After printing current date and time on screen, it waits for 1000 milliseconds(1 second) before printing it again on screen.

C program to make a digital clock using graphics

C Program to Make a Digital Clock Using C Graphics

#include <conio.h>
#include <graphics.h>
#include <time.h>
#include <dos.h>
#include <string.h>
 
int main() {
    int gd = DETECT, gm;
    int midx, midy;
    long current_time;
    char timeStr[256];
 
    initgraph(&gd, &gm, "C:\\TC\\BGI");
 
    /* mid pixel in horizontal and vertical axis */
    midx = getmaxx() / 2;
    midy = getmaxy() / 2;
 
    while (!kbhit()) {
        cleardevice();
        setcolor(WHITE);
        setfillstyle(SOLID_FILL, WHITE);
        rectangle(midx - 250, midy - 40, midx + 250, midy + 40);
        floodfill(midx, midy, WHITE);
        /* Get Current epoch time in seconds */
        current_time = time(NULL);
        /* store the date and time in string */
        strcpy(timeStr, ctime(&current_time));
        setcolor(RED);
        settextjustify(CENTER_TEXT, CENTER_TEXT);
        settextstyle(SANS_SERIF_FONT, HORIZ_DIR, 4);
 
        moveto(midx, midy);
        /* print current time */
        outtext(timeStr);
        /* Add delay of 1000 milliseconds(1 second) */
        delay(1000);
    }
 
    getch();
    closegraph();
    return 0;
}

Program Output
Here is the screen shot of digital clock that shows current date and time on screen.

DIGITAL_CLOCK