1

In shell scripting, when ever I want the local time I do something like

date +%s

from the command line and it returns me the current date and time in this format "1343221713"

I am wondering whether there is a way to achieve the same result in C

4

2 回答 2

4

Use time.h library in C

example:

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

int main()
{
    /* Obtain current time as seconds elapsed since the Epoch. */
    time_t clock = time(NULL);

    /* Convert to local time format and print to stdout. */
    printf("Current time is %s", ctime(&clock));
    return 0;
}

see more examples: http://en.wikipedia.org/wiki/C_date_and_time_functions

于 2012-07-25T13:54:47.110 回答
2

More flexible than time(3) is gettimeofday(3) as declared in sys/time.h

#include <sys/time.h>
#include <stdio.h>
int main(void)
{
        struct timeval tv = {0};
        gettimeofday(&tv, NULL);
        printf("seconds since epoch %ld, microseconds %ld\n", tv.tv_sec, tv.tv_usec);
        return 0;
}
于 2012-07-25T14:14:12.350 回答