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->tm_min=0; mytm->tm_hour=0; result = mktime(mytm); 

Above the code snippet, I expect the result to display the number of seconds elapsed since 1970, jan-1st for a given date. DD / MM / YYYY stored per day, month, year But I get a compilation error

error: dereferencing pointer to incomplete type

+4
source share
3 answers

You need

 #include <time.h> 

in your file to fix an incomplete type error.

Edit: given the day, month, year to find the time in seconds from January 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 that in ISO C, mktime() returns an integer value of type time_t that represents the time in the struct tm * argument, but the value of such an integral value is not necessarily β€œseconds since January 1, 1970.” This should not be in seconds. POSIX commits that time() , mktime() , etc., return seconds from January 1, 1970, so you should be fine. I mention above for completeness.

+3
source

The time function returns the number of seconds from January 1, 1970 UTC. You do not need to call any other functions. The time_t type is an integer type, probably equivalent to int.

+2
source

Dietrich is right, however, if you want to add the number of seconds since Epoch in a formatted string with different date information, you should consider using strftime() .

+1
source

Source: https://habr.com/ru/post/1299075/


All Articles