#include <stdio.h>
#include <time.h>
/*
time() → gets current time as seconds since 1970.
localtime() → converts it into a struct tm with fields like year, month, day, hour.
strftime() → formats the date/time using format specifiers.
format specifier:
%Y — 4‑digit year
%m — month (01–12)
%d — day of month
%H — hour (00–23)
%I — hour (01–12)
%M — minutes
%S — seconds
%A — full weekday name
%B — full month name
%c — locale’s default date/time
%j — day of year (001–366)
%W — week number (Mon-start)
%U — week number (Sun-start)
*/
#include <stdio.h>
#include <time.h>
int main() {
time_t now = time(NULL); // Get current timestamp
struct tm *t = localtime(&now); // Convert to local time components
char buf[128];
// --- Basic numeric formats ---
strftime(buf, sizeof(buf), "%Y-%m-%d", t);
printf("ISO format (YYYY-MM-DD): %s\n", buf);
strftime(buf, sizeof(buf), "%d/%m/%Y", t);
printf("European format (DD/MM/YYYY): %s\n", buf);
strftime(buf, sizeof(buf), "%m-%d-%Y", t);
printf("US format (MM-DD-YYYY): %s\n", buf);
// --- Time formats ---
strftime(buf, sizeof(buf), "%H:%M:%S", t);
printf("24-hour time: %s\n", buf);
strftime(buf, sizeof(buf), "%I:%M:%S %p", t);
printf("12-hour time: %s\n", buf);
// --- Full date with names ---
strftime(buf, sizeof(buf), "%A, %B %d, %Y", t);
printf("Full weekday + month name: %s\n", buf);
strftime(buf, sizeof(buf), "%a, %b %d", t);
printf("Short weekday + month name: %s\n", buf);
// --- Combined date/time ---
strftime(buf, sizeof(buf), "%Y-%m-%d %H:%M:%S", t);
printf("Full timestamp: %s\n", buf);
strftime(buf, sizeof(buf), "%c", t);
printf("Locale default date/time: %s\n", buf);
// --- Special formats ---
strftime(buf, sizeof(buf), "Day of year: %j", t);
printf("%s\n", buf);
strftime(buf, sizeof(buf), "Week number (Mon-start): %W", t);
printf("%s\n", buf);
strftime(buf, sizeof(buf), "Week number (Sun-start): %U", t);
printf("%s\n", buf);
return 0;
}
/*
run:
ISO format (YYYY-MM-DD): 2026-05-20
European format (DD/MM/YYYY): 20/05/2026
US format (MM-DD-YYYY): 05-20-2026
24-hour time: 09:04:58
12-hour time: 09:04:58 AM
Full weekday + month name: Wednesday, May 20, 2026
Short weekday + month name: Wed, May 20
Full timestamp: 2026-05-20 09:04:58
Locale default date/time: Wed May 20 09:04:58 2026
Day of year: 140
Week number (Mon-start): 20
Week number (Sun-start): 20
*/