Siksha Sarovar

Siksha Sarovar (sikshasarovar.com) is a free educational web application that helps students in India learn programming and prepare for academic and competitive exams. The platform offers structured coding courses (C, C++, Python, Java, HTML, CSS, PHP, Power BI, AI, Machine Learning, Data Science), complete university curriculum notes for BCA/MCA students with previous year question papers, Class 10 and Class 12 CBSE/HBSE school notes, and dedicated preparation material for SSC, UPSC, Banking, Railway and other government exams. Browsing the site is completely free and requires no account. Users may optionally sign in with Google solely to save their learning progress, quiz scores and personal preferences across devices.

Privacy Policy | Terms of Service | Contact Siksha Sarovar | About Siksha Sarovar

v4.0.9 · PWA
Siksha Sarovar logo
Siksha Sarovar
Your Learning Universe

Siksha Sarovar is a free e-learning platform for coding courses, BCA university notes and competitive exam preparation. Optional Google sign-in saves your learning progress across devices.

Initializing knowledge base…
Compiling modules 0%

Unit 4 — Standard Library: time.h

Lesson 24 of 32 in the free C Language notes on Siksha Sarovar, written by Rohit Jangra.

Standard Library: time.h

The time.h header provides functions for working with dates and times.

---

Key Types

TypeDescription
time_tInteger type representing time (seconds since epoch)
struct tmBroken-down time structure
clock_tProcessor clock ticks

---

time() Function

Returns the current calendar time as a time_t value (seconds since Jan 1, 1970).

#include <time.h>

time_t now = time(NULL);
printf("Seconds since epoch: %ld\n", (long)now);

---

localtime() — Convert to struct tm

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

int main() {
    time_t now = time(NULL);
    struct tm *t = localtime(&now);
    
    printf("Year: %d\n", t->tm_year + 1900);  /* years since 1900 */
    printf("Month: %d\n", t->tm_mon + 1);      /* 0-11 */
    printf("Day: %d\n", t->tm_mday);
    printf("Hour: %d\n", t->tm_hour);
    printf("Minute: %d\n", t->tm_min);
    printf("Second: %d\n", t->tm_sec);
    
    return 0;
}

---

struct tm Members

MemberRangeMeaning
tm_yearyears since 1900Year
tm_mon0–11Month
tm_mday1–31Day of month
tm_hour0–23Hour
tm_min0–59Minute
tm_sec0–60Second
tm_wday0–6Day of week (0=Sunday)
tm_yday0–365Day of year

---

ctime() — Convert to Readable String

time_t now = time(NULL);
printf("Current time: %s", ctime(&now));
/* Output: Mon Jan 15 10:30:00 2024 */

---

clock() — Measure Execution Time

#include <time.h>

clock_t start = clock();

/* ... code to measure ... */
for (int i = 0; i < 1000000; i++);

clock_t end = clock();
double elapsed = (double)(end - start) / CLOCKS_PER_SEC;
printf("Time: %.4f seconds\n", elapsed);

---

Using time() to Seed Random Numbers

#include <stdlib.h>
#include <time.h>

srand((unsigned int)time(NULL));
int random = rand() % 100;