BCA SCHOOL
Programming Tutorials • Notes • Practical • Books
LATEST TUTORIALS

Date & Time Functions in C: clock, time, gmtime, localtime | Unit 3 | BKNMU BCA

by BCA School



BKNMU Junagadh  |  BCA Sem 1  |  Unit 3

Date & Time Functions in C: clock, time, gmtime & localtime

Complete Guide to CPU Execution Time, System Epoch Timestamps, and struct tm Formatting

BKNMU Junagadh BCA Sem 1 Unit 3 time.h Header clock() & time() struct tm
In simple words: In C programming, measuring how fast your code runs and fetching current calendar dates require specialized library routines. All standard date and time capabilities are defined within the #include <time.h> header file. This guide covers four core functions: clock(), time(), gmtime(), and localtime(), tailored strictly for BKNMU BCA Semester 1 (Unit 3).
📖 Core Date & Time Functions Defined in time.h

The time.h library organizes time-tracking operations into four primary routines:

clock()

1. Processor Time

Calculates the total CPU clock ticks consumed by the running process since start. Divide by CLOCKS_PER_SEC to get seconds.

time()

2. Epoch Calendar Time

Fetches the current calendar time as total raw seconds elapsed since Jan 1, 1970 (Unix Epoch) returned as a time_t integer.

localtime()

3. Local Time Structure

Converts raw epoch seconds into a broken-down struct tm representation matched to the system's local timezone.

gmtime()

4. UTC / GMT Structure

Converts raw epoch seconds into a broken-down struct tm representing Greenwich Mean Time (UTC) without local offsets.

1️⃣ Master Table: Function Specifications

A quick breakdown of parameters, types, and return behaviors for each function:

Function Prototype Functional Purpose Return Value / Type
clock_t clock(void) Measures the total CPU processor execution time consumed by the program process. Returns clock ticks as clock_t (-1 if unavailable).
time_t time(time_t *timer) Retrieves the current system calendar timestamp in seconds elapsed since Jan 1, 1970. Returns epoch seconds as time_t.
struct tm* localtime(const time_t *t) Parses epoch seconds into broken-down local year, month, day, and clock components. Returns pointer to a static struct tm.
struct tm* gmtime(const time_t *t) Parses epoch seconds into broken-down UTC/GMT calendar components without offsets. Returns pointer to a static struct tm.
ℹ️ Key Data Structures in time.h:
  • time_t: Standard integer type holding elapsed seconds since Epoch.
  • clock_t: Arithmetic type storing CPU tick counts.
  • struct tm: Structure holding separated fields: tm_sec (0-59), tm_min (0-59), tm_hour (0-23), tm_mday (1-31), tm_mon (0-11, 0=Jan), tm_year (Years since 1900).
💻 Practical Code Examples

1. Benchmarking Execution Duration using clock():

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

int main() {
    clock_t start, end;
    double duration;

    start = clock();

    // Sample loop to consume CPU cycles
    for (long i = 0; i < 100000000; i++);

    end = clock();

    duration = ((double)(end - start)) / CLOCKS_PER_SEC;
    printf("Execution Time: %f seconds\n", duration);

    return 0;
}

2. Reading Local and UTC Dates using time(), localtime(), and gmtime():

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

int main() {
    time_t raw_time;
    struct tm *local, *utc;

    time(&raw_time); // Fetch epoch seconds

    // 1. Parse local timezone
    local = localtime(&raw_time);
    printf("Local Time: %02d/%02d/%d %02d:%02d:%02d\n",
           local->tm_mday,
           local->tm_mon + 1,     // Add 1 because tm_mon starts at 0
           local->tm_year + 1900, // Add 1900 because tm_year starts from 1900
           local->tm_hour,
           local->tm_min,
           local->tm_sec);

    // 2. Parse UTC / GMT timezone
    utc = gmtime(&raw_time);
    printf("UTC Time:   %02d/%02d/%d %02d:%02d:%02d\n",
           utc->tm_mday,
           utc->tm_mon + 1,
           utc->tm_year + 1900,
           utc->tm_hour,
           utc->tm_min,
           utc->tm_sec);

    return 0;
}
🔄 Step-by-Step Flow: How time.h Parses Dates
1

Step 1: Timestamp Acquisition

Calling time(NULL) reads the hardware clock and returns the count of seconds since Jan 1, 1970.

2

Step 2: Component Transformation

Passing that timestamp pointer into localtime() or gmtime() converts seconds into structured variables.

3

Step 3: Offsets & Formatting

Apply +1900 to tm_year and +1 to tm_mon to produce standard human-readable calendar values.

💡 Critical Exam Offsets: In BKNMU exams, remember that struct tm requires manual adjustments:
  • Year: Always calculate as local->tm_year + 1900.
  • Month: Always calculate as local->tm_mon + 1.
⚠️ Memory Warning: Static Buffer Overwrite: Both localtime() and gmtime() share the same statically allocated internal memory buffer. Each new call overwrites earlier results. Copy data out if you must keep multiple parsed timestamps.
📝 Quick Revision — Key Exam Points
  • Header: #include <time.h>
  • clock(): Measures CPU time; divide by CLOCKS_PER_SEC for seconds.
  • time(): Returns raw seconds since Unix Epoch (Jan 1, 1970).
  • localtime(): Returns local timezone structure pointer.
  • gmtime(): Returns standard UTC/GMT structure pointer.
  • Structure Fixes: Remember to adjust tm_mon + 1 and tm_year + 1900.