开发者

Get current date and time in seconds

    time_t rawtime;
struct tm *mytm;
time_t result;

time(&rawtime);

mytm=localtime(&rawtime);
mytm->tm_mon=month-1;
mytm->tm_mday=day;
mytm->tm_year=year-1900;

mytm->tm_sec=0;
mytm-&开发者_高级运维gt;tm_min=0;
mytm->tm_hour=0;

result = mktime(mytm);

Above code snippet,I'm expecting result to display the no.of seconds lapsed since 1970,jan-1st for the given date. DD/MM/YYYY stored in day ,month,year But i'm getting compile error

error: dereferencing pointer to incomplete type


You need

#include <time.h>

in your file to fix the error about incomplete type.

Edit: Given a day, month, year to find the time in seconds since Jan 1 1970 to midnight on that day:

struct tm mytm = { 0 };
time_t result;
mytm.tm_year = year - 1900;
mytm.tm_mon = month - 1;
mytm.tm_mday = day;
result = mktime(&mytm);
if (result == (time_t) -1) {
    /* handle error */
} else {
    printf("%lld\n", (long long) result);
}

Note the in ISO C, mktime() returns an integral value of type time_t that represents the time in the struct tm * argument, but the meaning of such an integral value is not necessarily "seconds since Jan 1, 1970". It need not be in seconds at all. POSIX mandates that time(), mktime(), etc., return seconds since Jan 1, 1970, so you should be OK. I mention the above for completeness.


The "time" function returns the number of seconds since Jan 1 1970 UTC. You do not need to call any other functions. The time_t type is just an integer type, it's probably equivalent to int.


Dietrich is correct, however if you wished to add the number of seconds since the Epoch in a formatted string with other date info, you should consider using strftime().

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜