get the current time in seconds

You can get the current time with gettimeofday (C11), time (Linux), or localtime_r (POSIX); depending on what calendar & epoch you're interested. You can convert it to seconds elapsed after calendar epoch, or seconds of current minute, whichever you are after:

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

int main() {
    time_t current_secs = time(NULL);
    localtime_r(&current_secs, &current_time);

    char secstr[128] = {};
    struct tm current_time;
    strftime(secstr, sizeof secstr, "%S", &current_time);

    fprintf(stdout, "The second: %s\n", secstr);
    return 0;
}

The following complete program shows you how to access the seconds value:

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

int main (int argc, char *argv[]) {
    time_t now;
    struct tm *tm;

    now = time(0);
    if ((tm = localtime (&now)) == NULL) {
        printf ("Error extracting time stuff\n");
        return 1;
    }

    printf ("%04d-%02d-%02d %02d:%02d:%02d\n",
        tm->tm_year+1900, tm->tm_mon+1, tm->tm_mday,
        tm->tm_hour, tm->tm_min, tm->tm_sec);

    return 0;
}

It outputs:

2010-02-11 15:58:29

How it works is as follows.

  • it calls time() to get the best approximation to the current time (usually number of seconds since the epoch but that's not actually mandated by the standard).
  • it then calls localtime() to convert that to a structure which contains the individual date and time fields, among other things.
  • at that point, you can just de-reference the structure to get the fields you're interested in (tm_sec in your case but I've shown a few of them).

Keep in mind you can also use gmtime() instead of localtime() if you want Greenwich time, or UTC for those too young to remember :-).


A more portable way to do this is to get the current time as a time_t struct:

time_t mytime = time((time_t*)0);

Retrieve a struct tm for this time_t:

struct tm *mytm = localtime(&mytime);

Examine the tm_sec member of mytm. Depending on your C library, there's no guarantee that the return value of time() is based on a number of seconds since the start of a minute.

Tags:

C