Display Current Date and Time

CCBeginner
Practice Now

Introduction

In C programming, the standard library provides some functions to handle date and time manipulation. In this lab, we will learn how to display the current date and time using the ctime function.

Note: You need to create the file ~/project/main.c yourself to practice coding and learn how to compile and run it using gcc.

cd ~/project
## create main.c
touch main.c
## compile main.c
gcc main.c -o main
## run main
./main

Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL c(("`C`")) -.-> c/UserInteractionGroup(["`User Interaction`"]) c(("`C`")) -.-> c/BasicsGroup(["`Basics`"]) c(("`C`")) -.-> c/PointersandMemoryGroup(["`Pointers and Memory`"]) c(("`C`")) -.-> c/FunctionsGroup(["`Functions`"]) c/UserInteractionGroup -.-> c/output("`Output`") c/BasicsGroup -.-> c/data_types("`Data Types`") c/BasicsGroup -.-> c/operators("`Operators`") c/PointersandMemoryGroup -.-> c/memory_address("`Memory Address`") c/FunctionsGroup -.-> c/function_declaration("`Function Declaration`") subgraph Lab Skills c/output -.-> lab-123236{{"`Display Current Date and Time`"}} c/data_types -.-> lab-123236{{"`Display Current Date and Time`"}} c/operators -.-> lab-123236{{"`Display Current Date and Time`"}} c/memory_address -.-> lab-123236{{"`Display Current Date and Time`"}} c/function_declaration -.-> lab-123236{{"`Display Current Date and Time`"}} end

Include Libraries

In this step, we will include the necessary libraries.

#include <stdio.h>
#include <time.h>

Declare Main Function

In this step, we will declare the main function and print a header message.

int main() {
    printf("\n\n\t\tDisplay Current Date and Time using C Program\n\n");

Declare Variables

In this step, we will declare the variable t with datatype time_t to store the current time.

time_t t;
time(&t);

Print Current Date and Time

In this step, we will print the current date and time using the ctime() function.

printf("\nCurrent time is: %s", ctime(&t));

Close Main Function

In this step, we will close the main function and return 0.

    return 0;
}

Summary

In this lab, we learned how to display the current date and time using the ctime function of the C programming language. By following the above steps, you should now be able to display the current date and time in your C programs.

Other C Tutorials you may like