Date and Time in C

Working with Date and Time in C programming to get Computer's current date and time in different formats by using a standard Time 'time.h' library of C programming language.

Program Printing Computer Current Time

Program

#include<stdio.h>
#include<conio.h>
#include<time.h> //including Library for working with Time and Date.
void main()
{
time_t now;
struct tm *tm_now;
now = time(NULL); //assigning Time to 'now'.
tm_now = localtime(&now); //assigning Local time to 'tm_now'.
printf("%s", ctime(&now)); //and printing.
printf("%s", asctime(tm_now)); //printing 'tm_now' value.
getch();
}
Output
Fri Mar 17 19:47:28 2023
Fri Mar 17 19:47:28 2023

Program Printing Complete Current Data and Time

Program

#include<stdio.h>
#include<conio.h>
#include<time.h>
void main()
{
time_t now;
struct tm *tm_now;
char buff[BUFSIZ];
now = time(NULL); //assigning Time to 'now'.
tm_now = localtime(&now); //assigning Local Time to 'tm_now'.
strftime(buff, sizeof buff, "%A, %x %X %p", tm_now); //and printing.
printf("%s\n", buff);
getch();
}
Output
Friday, 03/17/23 19:48:22 PM

Program Printing Complete Current Data and Time Another Method

Program

#include<stdio.h>
#include<conio.h>
#include<Windows.h> //including Library for working with Windows.
void main()
{
SYSTEMTIME str_t; //'str_t' is object of 'SYSTEMTIME'.
GetSystemTime(&str_t); //getting System Time. and printing.
printf("Year: %d\nMonth: %d\nDate: %d\nHour: %d\nMin: %d\nSecond: %d\n",
        str_t.wYear, str_t.wMonth, str_t.wDay, str_t.wHour, str_t.wMinute, str_t.wSecond);
getch();
}
Output
Year: 2023
Month: 3
Date: 17
Hour: 14
Min: 51
Second: 44

Program User Enter Date Using as a Computer Date
Program

#include<stdio.h>
#include<conio.h>
#include<time.h> //including Library for working with Time.
void main()
{
struct tm str_time; //'str_time' is object.
time_t time_of_day; //'time_of_day' is object of 'time_t'.
str_time.tm_year = 2012-1900; //assigning values.
str_time.tm_mon = 6;
str_time.tm_mday = 5;
str_time.tm_hour = 10;
str_time.tm_min = 3;
str_time.tm_sec = 5;
str_time.tm_isdst = 0;
time_of_day = mktime(&str_time); //assigning new date.
printf(ctime(&time_of_day)); //and printing.
getch();
}
Output
Thu Jul 05 10:03:05 2012