C library - time() function



The C library time() function returns the time since the Epoch (00:00:00 UTC, January 1, 1970), measured in seconds. If seconds is not NULL, the return value is also stored in variable seconds.

In context of time() function, Epoch determine the timestamp value which is date and time.

Syntax

Following is the syntax of the C library time() function −

time_t time(time_t *t)

Parameters

This function takes only single parameter −

  • seconds − This is the pointer to an object of type time_t, where the seconds value will be stored.

Return Value

This function return current calendar time as a time_t object.

Example 1

Following is the basic C library program to see the demonstration of time() function.

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

int main () {
   time_t seconds;

   seconds = time(NULL);
   printf("Hours since January 1, 1970 = %ld\n", seconds/3600);
  
   return(0);
}

Output

The above code produces the following result −

Hours since January 1, 1970 = 393923

Example 2

Here, we measure the time value in second using the time() function.

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

int main()
{
   time_t sec;
   // Store time in seconds
   time(&sec);
   printf("Seconds since January 1, 1970 = %ld\n", sec);
   return 0;
}

Output

After executing the above code, we get the following result −

Seconds since January 1, 1970 = 1715856016

Example 3

In this example, we use time() function to return the current calendar time as the number of seconds. So, the resultant value is preferred as a unix timestamp.

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

int main(void) {
    // Get the current time
    time_t now = time(NULL);

    printf("Current timestamp: %ld\n", now);

    // Convert to local time
    struct tm *local_time = localtime(&now);
    printf("Local time: %s", asctime(local_time));

    // Calculate a new time (add 1 minute)
    local_time -> tm_min += 1;
    time_t new_time = mktime(local_time);
    printf("New timestamp (1 minute later): %ld\n", new_time);

    // Format the time
    char formatted_time[100];
    strftime(formatted_time, sizeof(formatted_time), "%l %p", local_time);
    printf("Formatted time: %s\n", formatted_time);

    // Measure execution time
    clock_t start = clock();
    for (int i = 0; i < 100000000; ++i) { }
    clock_t end = clock();

    double total_time = (double)(end - start) / CLOCKS_PER_SEC;
    printf("Execution time: %.6f seconds\n", total_time);

    return 0;
}

Output

On execution of above code, we get the following result −

Current timestamp: 1715853945
Local time: Thu May 16 10:05:45 2024
New timestamp (1 minute later): 1715854005
Formatted time: 10 AM
Execution time: 0.213975 seconds
Advertisements