Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

get the current time in seconds

Tags:

c

I am wondering is there any function that would return the current time in seconds, just 2 digits of seconds? I'm using gcc 4.4.2.

like image 905
ant2009 Avatar asked Feb 11 '10 07:02

ant2009


3 Answers

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 :-).

like image 61
paxdiablo Avatar answered Nov 14 '22 02:11

paxdiablo


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.

like image 2
CB Bailey Avatar answered Nov 14 '22 04:11

CB Bailey


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;
}
like image 2
Michael Foukarakis Avatar answered Nov 14 '22 03:11

Michael Foukarakis