C Date and Time

C Date and Time

In C programming, working with date and time is done using functions defined in the <time.h> library.

This library allows you to:

  • Get the current date and time

  • Format date/time

  • Measure execution time

  • Convert between time formats


📌 Common Data Type Used: time_t

time_t stores calendar time in seconds since January 1, 1970 (Unix Epoch).


1️⃣ Get Current Date and Time

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

int main() {
time_t now;
time(&now);

printf("Current time: %s", ctime(&now));
return 0;
}

Output (example):

Current time: Tue Dec 03 15:42:10 2025

2️⃣ Using localtime() to Break Down Time

You can extract year, month, day, time components using struct tm.

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

int main() {
time_t now = time(NULL);
struct tm *local = localtime(&now);

printf("Year: %d\n", local->tm_year + 1900);
printf("Month: %d\n", local->tm_mon + 1);
printf("Day: %d\n", local->tm_mday);
printf("Time: %02d:%02d:%02d\n", local->tm_hour, local->tm_min, local->tm_sec);

return 0;
}


3️⃣ Formatting Time Using strftime()

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

int main() {
time_t now = time(NULL);
struct tm *local = localtime(&now);

char buffer[40];
strftime(buffer, sizeof(buffer), "%d-%m-%Y %H:%M:%S", local);

printf("Formatted Time: %s\n", buffer);
return 0;
}

Output:

Formatted Time: 03-12-2025 15:45:10

4️⃣ Calculating Time Differences

You can measure how long something takes using difftime().

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

int main() {
time_t start, end;

time(&start);
printf("Processing...\n");

for(long i=0; i<500000000; i++); // some heavy task

time(&end);

printf("Time taken: %.2f seconds\n", difftime(end, start));
return 0;
}


5️⃣ Converting struct tm Back to time_t

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

int main() {
struct tm date = {0};
date.tm_year = 2025 - 1900;
date.tm_mon = 11; // December (0-based)
date.tm_mday = 25;

time_t t = mktime(&date);

printf("Unix timestamp: %ld\n", t);
return 0;
}


📌 Summary Table

Function Purpose
time() Returns current time in seconds
ctime() Converts time to readable string
localtime() Converts time_t to structured time
strftime() Formats date/time into a custom string
difftime() Calculates time difference
mktime() Converts structured time back to time_t

CodeCapsule

Sanjit Sinha — Web Developer | PHP • Laravel • CodeIgniter • MySQL • Bootstrap Founder, CodeCapsule — Student projects & practical coding guides. Email: info@codecapsule.in • Website: CodeCapsule.in

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *